File Handling In Python – Python Read And Write File
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Yesterday, we told you about File I/O in Python. Today we will see File Handling in Python in which we study: Python Read file, Python Write File, Python Open File, and Python Close File.
Along with this, we will learn Python File Methods with their syntax and examples.
So, let’s start exploring File Handling in Python.
What is Python Read and Write File?
In our previous article, we saw Python open, close, read, and write to file. Let’s take examples for each of Python Read and Write File.
1. Python Open File
In Python, to open a file, we use the open() method.
>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','r+')
We may choose out of many opening modes for a file:
Mode | Description |
r | To read a file (default) |
w | To write a file; Creates a new file if it doesn’t exist, truncates if it does |
x | Exclusive creation; fails if file already exists |
a | To append at the end of file; create if doesn’t exist |
t | Text mode (default) |
b | Binary mode |
+ | To open a file for updating (reading or writing) |
2. Python Close File
To close a file in Python, we use the close() method.
>>> todo.close()
A safer practice is to put it inside a try..finally block.
>>> try: todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','r+') print(1/0) finally: todo.close()
Output
Traceback (most recent call last):File “<pyshell#127>”, line 3, in <module>
print(1/0)
ZeroDivisionError: division by zero
We can also use the with-statement so that the file automatically closes as the code under it finishes executing.
>>> with open('C:\\Users\\lifei\\Desktop\\To do.txt','r+') as todo: todo.read()
Output
3. Python Read File
To read from a file in Python, we call the read() method on the file object.
>>> type(todo)
Output
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','r') >>> todo.read(3)
Output
>>> todo.read()
Output
>>> todo.read()
Output
When we provide an argument to read(), it reads that many characters. After that, calling read() reads from where the cursor is right now.
To find the cursor’s position, and to reposition it, we use the seek() and tell() methods respectively.
>>> todo.tell()
Output
>>> todo.seek(8)
Output
>>> todo.read()
Output
4. Python readline() and readlines()
The method readline() reads one line at a time.
>>> todo.seek(0)
>>> todo.readline()
Output
>>> todo.readline()
Output
>>> todo.readline()
Output
Now, the readlines() method prints the rest of the file.
>>> todo.readlines()
Output
Otherwise, we can also iterate on a file using a for-loop.
>>> todo.seek(0)
>>> for line in todo: print(line,end='')
Output
Organize room
Print labels
Write article
Study for exam
Learn to cook
5. Python Write to File
To be able to write to a file in Python, we must first open it in ‘a’, ‘w’, or ‘x’ mode. Refer to the table above to find out more about these.
Let’s first close the file.
>>> todo.close() >>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','a') >>> todo.write('Write to the end of the file')
Output
>>> todo.close() >>> with open('C:\\Users\\lifei\\Desktop\\To do.txt','r') as todo: todo.read()
Output
Any Doubt yet in File handling in Python? Please comment.
Python Read and Write File – Python File Methods
Let’s now look at some methods to deal with Python Read and Write File.
1. close() in Python
With close(), we close a file to free up the resources held by it.
>>>todo.close()
You must always close a file after you’re done working with it. Check section 2b above.
2. detach() in Python
This detaches the underlying binary buffer from TextIOBase and returns it.
>>> todo.detach()
Output
>>> todo.read()
Output
Traceback (most recent call last):File “<pyshell#171>”, line 1, in <module>
todo.read()
ValueError: underlying buffer has been detached
After detaching from the buffer, when we try to read the file, it raises a ValueError.
3. fileno() in Python
fileno() returns a file descriptor of the file. This is an integer number.
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt') >>> todo.fileno()
Output
>>> todo.fileno()
Output
>>> myfile=open('C:\\Users\\lifei\\Desktop\\Today.txt') >>> myfile.fileno()
Output
>>> gifts=open('C:\\Users\\lifei\\Desktop\\gifts.jpg') >>> gifts.fileno()
Output
>>> one=open('C:\\Users\\lifei\\Desktop\\1.txt') >>> one.fileno()
Output
>>> one.read()
Output
4. flush() in Python
flush() writes the specified content from the program buffer to the operating system buffer in event of a power cut.
>>> todo.flush() >>>
5. isatty() in Python
This method returns True if the file is connected to a tty-like device.
>>> todo.isatty()
Output
6. read(n) in Python
This lets us read n characters from a file.
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt') >>> todo.read(5)
Output
7. readable() in Python
This returns True if the object is readable.
>>> todo.readable()
Output
>>> todo.close() >>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','a') >>> todo.readable()
Output
>>> todo.close()
8. readline(n=-1) in Python
readline() reads the next line.
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt') >>> todo.readline()
Output
>>> todo.readline(5)
Output
>>> todo.readline(2)
Output
>>> todo.readline()
Output
>>> todo.readline(5)
Output
>>> todo.readline(-1)
Output
9. readlines() in Python
This one reads the rest of the lines.
>>> todo.seek(0)
>>> todo.readlines(0)
Output
>>> todo.seek(0)
>>> todo.readlines(1)
Output
10. seek() in Python
seek() lets us reposition the cursor to the specified position.
>>> todo.seek(3)
Output
11. seekable() in Python
This returns True if the file stream supports random access.
>>> todo.seekable()
Output
12. tell() in Python
tell() tells us the current position of the cursor.
>>> todo.tell()
Output
13. truncate() in Python
truncate() resizes the file. You must open your file in a writing mode for this.
We have To do.txt sized 118 bytes currently. Let’s resize it to 100 bytes.
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','a') >>> todo.truncate(100)
Output
This returned the new size. We even went to our desktop and checked, it indeed resized it.
But in doing this, it truncated some of the content of the file from the end.
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt') >>> todo.read()
Output
When we provide no argument, it resizes to the current location.
14. writable() in Python
This returns True if the stream can be written to.
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt') >>> todo.writable()
Output
15. write(s) in Python
This method takes string ‘s’, and writes it to the file. Then, it returns the number of characters written.
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','a') >>> todo.write('\nWrite assignment')
Output
>>> todo.close() >>> with open('C:\\Users\\lifei\\Desktop\\To do.txt') as todo: todo.read()
Output
16. writelines() in Python
writelines() writes a list of lines to a file.
>>> with open('C:\\Users\\lifei\\Desktop\\To do.txt','a') as todo:
Output
>>> with open('C:\\Users\\lifei\\Desktop\\To do.txt') as todo:
Output
Organize room
Print labels
Write article
Study for exam
Learn to cookWrite to the
Write assignment
One
Two
Three
So this was all about file handling in Python and Python read and write file.
Python Interview Questions on File Handling
- What is file handling in Python?
- How do you handle a file in Python?
- What is the use of file handling in Python?
- Give an example for file handling in Python.
- What is stored in file handle in Python?
Conclusion
After this article, we hope you’ve revised Python Read and Write File, what we saw in the previous one, and learned something new.
If you can’t understand something in File Handling in Python , ask us in the comments.
Hope you like the File Handling in Python tutorial.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google
i already write to and the output is 34 but i not able to see that string in my file
Hello Rohit,
Thanks for commenting on file handling in Python. You should try flushing the buffer to the disk, and then closing and re-opening your file to check again.
Hope, it helps!
I hvae CSV file in local folder? Through python script am loading postgreSQL table, when I run the script am getting error
ERROR: FileNotFoundError: [WinError 2] The system cannot find the file specified : ‘C:\\Project\\test.csv’
For this solution is here :The container is running some version of linux and that can’t use a UNC path. You will need to switch to another method to retrieve the CSV file. could you please suggest me the another method ?
The open() method is the only inbuilt function that opens any file in python. The error you are getting is because your operating system cannot figure out the exact file location. If your script and CSV file is in same folder then open(“test.csv”, “r”) would work for you.
If you are working with CSV then you can also try using pandas
import pandas as pd
data = pd.read_csv(“filename.csv”)
print(data)