File Handling In Python – Python Read And Write File

Free Python courses with 57 real-time projects - 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.

File Handling in Python - Python Read And Write File

File Handling in Python – Python Read And Write File

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:

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)

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

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

3. Python Read File

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

>>> type(todo)

Output

<class ‘_io.TextIOWrapper’>
>>> todo=open('C:\\Users\\lifei\\Desktop\\To do.txt','r')
>>> todo.read(3)

Output

‘Get’
>>> todo.read()

Output

‘ groceries\nOrganize room\nPrint labels\nWrite article\nStudy for exam\nLearn to cook’
>>> 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

88
>>> todo.seek(8)

Output

8
>>> todo.read()

Output

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

4. Python readline() and readlines()

The method readline() reads one line at a time.

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

Output

‘Get groceries\n’
>>> todo.readline()

Output

‘Organize room\n’
>>> todo.readline()

Output

‘Print labels\n’

Now, the readlines() method prints the rest of the file.

>>> todo.readlines()

Output

[‘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='')

Output

Get groceries
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

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

Output

‘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 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

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

<_io.BufferedRandom name=’C:\\Users\\lifei\\Desktop\\To do.txt’>
>>> 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

4
>>> todo.fileno()

Output

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

Output

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

Output

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

Output

6
>>> 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

False

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

‘Get g’

7. readable() in Python

This returns True if the object is readable.

>>> todo.readable()

Output

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

Output

False
>>> 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

‘Get groceries\n’
>>> todo.readline(5)

Output

‘Organ’
>>> todo.readline(2)

Output

‘iz’
>>> todo.readline()

Output

‘e room\n’
>>> todo.readline(5)

Output

‘Print’
>>> todo.readline(-1)

Output

‘ labels\n’

9. readlines() in Python

This one reads the rest of the lines.

>>> todo.seek(0)
>>> todo.readlines(0)

Output

[‘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)

Output

[‘Get groceries\n’]

10. seek() in Python

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

>>> todo.seek(3)

Output

3

11. seekable() in Python

This returns True if the file stream supports random access.

>>> todo.seekable()

Output

True

12. tell() in Python

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

>>> todo.tell()

Output

118

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

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

Output

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

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

False

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

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

Output

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

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

todo.writelines([‘\nOne’,’\nTwo’,’\nThree’])
>>> with open('C:\\Users\\lifei\\Desktop\\To do.txt') as todo:

Output

print(todo.read())Get groceries
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

  1. What is file handling in Python?
  2. How do you handle a file in Python?
  3. What is the use of file handling in Python?
  4. Give an example for file handling in Python.
  5. 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.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

4 Responses

  1. rohit says:

    i already write to and the output is 34 but i not able to see that string in my file

    • DataFlair Team says:

      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!

  2. murali says:

    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 ?

    • DataFlair Team says:

      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)

Leave a Reply

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