Python File Open
- Previous Page Python File Open
- Next Page Python File Write/Create
Open a file on the server
Assuming we have the following files, located in the same folder as Python:
demofile.txt
Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck!
To open a file, please use the built-in open()
function.
open()
The function returns a file object, which has a read()
The method is used to read the content of the file:
Instance
f = open("demofile.txt", "r") print(f.read())
Read only a part of the file
By default,read()
The method returns the entire text, but you can also specify the number of characters to return:
Instance
Returns the first five characters of the file:
f = open("demofile.txt", "r") print(f.read(5))
Read Line
You can use readline()
The method returns a line:
Instance
Read a line from the file:
f = open("demofile.txt", "r") print(f.readline())
Through two calls readline()
You can read the first two lines:
Instance
Read two lines from the file:
f = open("demofile.txt", "r") print(f.readline()) print(f.readline())
By traversing the lines in the file through a loop, you can read the entire file line by line:
Instance
Traverse the file line by line:
f = open("demofile.txt", "r") for x in f: print(x)
Close File
It is a good habit to always close the file after completion.
Instance
Close the file after completion:
f = open("demofile.txt", "r") print(f.readline()) f.close()
Note:In some cases, due to buffering, you should always close the file, and changes made to the file before closing may not be displayed.
- Previous Page Python File Open
- Next Page Python File Write/Create