In this Python, you will learn everything about the Python file read operation 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.
Headings of Contents
Open a File on the Server
Here we will see the complete process of opening and reading the file from the server. Assume you have a file “myfile.txt” 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 the above code you will get output.
Output:
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
If the file is located in a different location, you have to provide a 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 the first two lines of the file.
Loop Through File Line.
You can loop through the 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