Menu Close

Python File Read

In this Python, you will learn how to read files from the machine or server and local machine with the help of examples. In the previous Python file handling tutorials, we have seen the basics of Python file handling.

Note:- To understand this tutorial, you should have basic knowledge of Python programming.

Open a File on the Server

Here we will see the complete process of open and read the file from the server. Assume you have a file “myfile.txt” on the same folder on the server or local machine ( Your Computer) and contains some data.

myfile.txt:

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

To open the file, use built-in open() function.

f = open("myfile.txt",'r")
print(f.read())

After executing above code you will get output.

Output:

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

If the file located on the different location, you have to provide path of that file like this.

f = open("D:\\myfiles\myfile.txt"",'r")
print(f.read())

Read only part of the file.

By default read() method returns a file object, which has a read() method that is used to read the whole content of the file.

f = open("myfile.txt","r")
print(f.read(10))

Read line of the File

To read only one line from the file use readline() method.

f = open("myfile.txt","r")
print(f.readline())

If you call readline() two times then you will get first two line of the file.

Loop Through File Line.

You can loop through file line by line Python for loop.

f = open("myfile.txt","r")
for i in f:
print(i)

Close the File

It is good practice to close the file after it open, to close the file, use close() method.

f = open("myfile.txt","r")
print(f.readline())
f.close()

Conclusion

In this python file handling article, you have got knowledge of how to open a file on the server and read the contents from the file. If you like this Python file open tutorial, please share and keep visiting for further Python tutorials.

For Reference:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts