Python read mode

Python File Open
Open a File on the Server
Suppose that we have the following file, located in the same folder as python:

Hello! Welcome to demofile.txt

This file is for testing purposes.

Good Luck!


Now, to open the file, use the built in open() function.

The open() function has a read() method for reading the content of the file and it returns a file object, which :

f = open("demofile.txt", "r")

print(f.read())


Read Only Parts of the File
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:

f = open("demofile.txt", "r")

print(f.read(5))


Read Lines
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:

f = open("demofile.txt", "r")

print(f.readline())


If you want to read the first two lines then at that time you can call readline() function two times.
For better understanding consider the following example:

f = open("demofile.txt", "r")

print(f.readline())

print(f.readline())


You can read the whole file by looping through the lines of the file, line by line:
Example: Loop through the file line by line:

f = open("demofile.txt", "r")

for x in f:

     print(x)


Close Files
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:

f = open("demofile.txt", "r")

print(f.readline())

f.close()


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.