Python File Open Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck!
Open a File on the Server
Suppose that we have the following file, located in the same folder as python:
Now, to open the file, use the built in open() function. f = open("demofile.txt", "r") print(f.read())
The open() function has a read() method for reading the content of the file and it returns a file object, which :
Read Only Parts of the File f = open("demofile.txt", "r") print(f.read(5))
By default the read() method returns the whole text, but you can also specify that how many characters you want to return:
For e.g. if you want to return the 5 first characters of the file, then you write he following code:
Read Lines f = open("demofile.txt", "r") print(f.readline())
You can also return only one line by using the readline() method:
For e.g. if you want to read one line of the file, then we write the following code:
If you want to read the first two lines then at that time you can call readline() function two times.
f = open("demofile.txt", "r") print(f.readline()) print(f.readline())
For better understanding consider the following example:
You can read the whole file by looping through the lines of the file, line by line:
f = open("demofile.txt", "r") for x in f:      print(x)
Example: Loop through the file line by line:
Close Files f = open("demofile.txt", "r") print(f.readline()) f.close()
It is always a good practice to always close the file when you are done with it.
Close the file when you are finish with it:
Note: You should always close your files, as in some cases, due to buffering, the changes that you have made to a file may not show until you close the file.