File Handling In Python – Python Read And Write File

1. File Handling in 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.

File Handling in Python - Python Read And Write File

File Handling in Python – Python Read And Write File

2. A Revision – 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.

Let’s revise Python Syntax & Python Dictionaries

a. 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:

ModeDescription
rTo read a file (default)
wTo write a file; Creates a new file if it doesn’t exist, truncates if it does
xExclusive creation; fails if file already exists
aTo append at the end of file; create if doesn’t exist
tText mode (default)
bBinary mode
+To open a file for updating (reading or writing)

b. 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()

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()

‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for exam\nLearn to cook’
To know more about Python Errors and Error & Exception Handling in Python, follow these link.

c. Python Read File

To read from a file in Python, we call the read() method on the file object.

>>> type(todo)

<class ‘_io.TextIOWrapper’>

>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','r')
>>> todo.read(3)

‘Get’

>>> todo.read()

‘ groceries\nOrganize room\nPrint labels\nWrite article\nStudy for exam\nLearn to cook’

>>> todo.read()


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()

88

>>> todo.seek(8)

8

>>> todo.read()

‘eries\nOrganize room\nPrint labels\nWrite article\nStudy for exam\nLearn to cook’
Python readline() and readlines()
The method readline() reads one line at a time.

>>> todo.seek(0)
>>> todo.readline()

‘Get groceries\n’

>>> todo.readline()

‘Organize room\n’

>>> todo.readline()

‘Print labels\n’
Now, the readlines() method prints the rest of the file.

>>> todo.readlines()
[‘Write article\n’, ‘Study for exam\n’, ‘Learn to cook’] Otherwise, we can also iterate on a file using a for-loop.

>>> todo.seek(0)
>>> for line in todo:
	print(line,end='')

Get groceries
Organize room
Print labels
Write article
Study for exam
Learn to cook

d. 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')

28

>>> todo.close()
>>> with open('C:\\Users\\lifei\\Desktop\\To do.txt','r') as todo:
	todo.read()

‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for exam\nLearn to cookWrite to the end of the file’

Any Doubt yet in File handling in Python? Please comment.

Python Interview Questions

3. Python Read and Write File – Python File Methods

Let’s now look at some methods to deal with Python Read and Write File.

Python Read and Write File - Python File Methods

Python Read and Write File – Python File Methods

a. 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.

b. detach() in Python

This detaches the underlying binary buffer from TextIOBase and returns it.

>>> todo.detach()

<_io.BufferedRandom name=’C:\\Users\\lifei\\Desktop\\To do.txt’>

>>> todo.read()

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.

c. 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()

4

>>> todo.fileno()

4

>>> myfile=open('C:\\Users\\lifei\\Desktop\\Today.txt')
>>> myfile.fileno()

3

>>> gifts=open('C:\\Users\\lifei\\Desktop\\gifts.jpg')
>>> gifts.fileno()

5

>>> one=open('C:\\Users\\lifei\\Desktop\\1.txt')
>>> one.fileno()

6

>>> one.read()

d. 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()
>>>

e. isatty() in Python

This method returns True if the file is connected to a tty-like device.

>>> todo.isatty()

False

f. 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)

‘Get g’

g. readable() in Python

This returns True if the object is readable.

>>> todo.readable()

True

>>> todo.close()
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','a')
>>> todo.readable()

False

>>> todo.close()

h. readline(n=-1) in Python

readline() reads the next line.

>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt')
>>> todo.readline()

‘Get groceries\n’

>>> todo.readline(5)

‘Organ’

>>> todo.readline(2)

‘iz’

>>> todo.readline()

‘e room\n’

>>> todo.readline(5)

‘Print’

>>> todo.readline(-1)

‘ labels\n’

i. readlines() in Python

This one reads the rest of the lines.

>>> todo.seek(0)
>>> todo.readlines(0)
[‘Get groceries\n’, ‘Organize room\n’, ‘Print labels\n’, ‘Write article\n’, ‘Study for exam\n’, ‘Learn to cookWrite to the end of the fileHi’]
>>> todo.seek(0)
>>> todo.readlines(1)
[‘Get groceries\n’]

j. seek() in Python

seek() lets us reposition the cursor to the specified position.

>>> todo.seek(3)

3

k. seekable() in Python

This returns True if the file stream supports random access.

>>> todo.seekable()

True

l. tell() in Python

tell() tells us the current position of the cursor.

>>> todo.tell()

118

m. 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)

100
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()

‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for exam\nLearn to cookWrite to the’
When we provide no argument, it resizes to the current location.

n. writable() in Python

This returns True if the stream can be written to.

>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt')
>>> todo.writable()

False

o. 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')

17

>>> todo.close()
>>> with open('C:\\Users\\lifei\\Desktop\\To do.txt') as todo: todo.read()

‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for exam\nLearn to cookWrite to the\nWrite assignment’

p. writelines() in Python

writelines() writes a list of lines to a file.

>>> with open('C:\\Users\\lifei\\Desktop\\To do.txt','a') as todo:

todo.writelines([‘\nOne’,’\nTwo’,’\nThree’])

>>> with open('C:\\Users\\lifei\\Desktop\\To do.txt') as todo:

print(todo.read())

Get groceries
Organize room
Print labels
Write article
Study for exam
Learn to cookWrite to the
Write assignment
One
Two
Three

Let’s look at Python Operators & Python Collection Modules

So this was all about file handling in Python and Python read and write file.

4. 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.
See Also- Python Jobs & Python Closure Nested
For reference

Leave a Reply

Your email address will not be published. Required fields are marked *