Python File i/o – Python Write to File and Python Read File

1. Python File i/o & File Read and Write

An important component of an operating system is its file and directories. We’ve talked about Python Directories. In that, we learned to manipulate (create, rename, delete,..) directories. Today, we will talk about Python file I/O. After this lesson, you will be able to Python open file, Python close file, Python read file, and Python writes to file. Let’s begin.

Python File I/O - Introduction

Python File I/O – Introduction

2. What is Python File?

A file is a location on disk that stores related information and has a name. A hard-disk is non-volatile, and we use files to organize our data in different directories on a hard-disk. The RAM (Random Access Memory) is volatile; it holds data only as long as it is up. So, we use files to store data permanently. To read from or write to a file, we must first open it. And then when we’re done with it, we should close it to free up the resources it holds (Open, Read/Write, Close).

3. Python Open File

To start Python file i/o, we deal with files and have a few in-built functions and methods in Python. To open a file in Python, we use the read() method.

But first, let’s get to the desktop, and choose a file to work with.

>>> import os
>>> os.getcwd()

‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’

>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.listdir()
[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Backup iPhone7+ 20-1-18’, ‘Burn Book.txt’, ‘ch’, ‘desktop.ini’, ‘dmkidnap.png’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipse Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘gifts.jpg’, ‘Items for trip.txt’, ‘Major temp’, structure’, ‘office temp.jpg’, ‘Papers’, ‘Remember to remember.txt’, ‘To do.txt’, ‘Today.txt’] If this seems new to you, be sure to check out Python Directory.
Now, let’s open Python file ‘To do.txt’.

>>> open('To do.txt')

<_io.TextIOWrapper name=’To do.txt’ mode=’r’ encoding=’cp1252′>

But to work with this, we must store it into a Python variable. Let’s do this.

>>> todo=open('To do.txt')
>>> todo

<_io.TextIOWrapper name=’To do.txt’ mode=’r’ encoding=’cp1252′>

We wouldn’t have to change directory if we just passed the full path of Python file to open(). But let’s work with this for now.

Follow this link to know more about Python Functions

Python File I/O - Python Open File

Python File I/O – Python Open File

a. Python File Modes

While opening Python file, we can declare our intentions by choosing a mode. We have the following modes:

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 a file already exists
aTo append at the end of the file; create if doesn’t exist
tText mode (default)
bBinary mode
+To open a file for updating (reading or writing)

Let’s take a couple of examples.

>>> todo=open('To do.txt','r+b') #To read and write in binary mode
>>> todo=open('To do.txt','a')

b. Choosing Your Encoding

Also, it is good practice to specify what encoding we want, because different systems use a different encoding. While Windows uses ‘cp1252’, Linux uses ‘utf-8’.

>>> todo=open('To do.txt',mode='r',encoding='utf-8')

c. When Python File Doesn’t Exist

Finally, if you try opening Python file that doesn’t exist, the interpreter will throw a FileNotFoundError.

>>> todo=open('abc.txt')

Traceback (most recent call last):

File “<pyshell#27>”, line 1, in <module>

todo=open(‘abc.txt’)

FileNotFoundError: [Errno 2] No such file or directory: ‘abc.txt’

Tell us how do you like the Python Open file Explanation.

4. Python Close File

When we tried to manually go rewrite the Python file, it threw this error dialog when we attempted to save it.
So, remember, always close what you open:

>>> todo.close()
Python File I/O - Python Close File

Python File I/O – Python Close File

a. Try..finally in Python

But if an exception occurs in the middle of our code, the file remains open, and the resources aren’t freed. To take care of these situations, we put the close() method in the finally-block.

>>> try:
                f=open('To do.txt')
                print("Before")
                print(1/0)
finally:
                f.close()

Before

Traceback (most recent call last):

File “<pyshell#51>”, line 4, in <module>

print(1/0)

ZeroDivisionError: division by zero

Follow this link, to handle an exception in Python

b. With

If you think having to put close() every time you’re done with a Python file is bunk, use the ‘with’ statement.

>>> with open('To do.txt') as f:
        f.read()

‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for exam’
With this, it will close the file implicitly as soon as it finishes executing the statements under the block.

5. Python Read File

To read the contents of a Python file, we can do one of these:

Python Read File

Python File I/o – Python Read File

a. The read() Method

We can use the read() method to read what’s in a Python file.

>>> with open('To do.txt') as todo:
          todo.read()

‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for examLearn to cook\nLearn to cook’
When we provide an integer argument to read(), it reads that many characters from the beginning of the Python file.

>>> todo=open('To do.txt')
>>> todo.read(5)

‘Get g’
Now when we call read() without any arguments, it reads the rest of the Python file.

>>> todo.read()

‘roceries\nOrganize room\nPrint labels\nWrite article\nStudy for examLearn to cook\nLearn to cook’
Notice that it prints a ‘\n’ for a newline. And when we yet read it, it prints an empty string, because the cursor has reached the end of the Python file.

>>> todo.read()
''
>>> todo.close()

b. Seek() and tell()

Okay, jokes apart, these two methods let us reposition the cursor and find its position. tell() tells us where the cursor is.

>>> todo=open('To do.txt')
>>> todo.read(5)

‘Get g’

>>> todo.tell()

5
seek() takes an integer argument, and positions the cursor after that many characters in the Python file. Along with that, it returns this new position of the cursor.

>>> todo.seek(0)
>>> todo.read()

‘Get groceries\nOrganize room\nPrint labels\nWrite article\nStudy for examLearn to cook\nLearn to cook’
seek() and tell() are like seekg(), seekp(), tellg(), and tellp() in C++.

c. Using Python For-loop

We can simply use a for-loop to iterate on a file. This is the beauty of Python- it simplifies everything.

>>> for line in open('To do.txt'):
           print(line,end='')

Get groceries
Organize room
Print labels
Write article
Study for exam
Learn to cook
We used the ‘end’ parameter to prevent the interpreter from adding extra newlines to each output. Otherwise, the output would have looked like this:

>>> for line in open('To do.txt'):
         print(line)

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

d. Readline()

Alternatively, the method readline() lets us read one line at a time. Simply put, the interpreter stops after every ‘\n’.

>>> todo=open('To do.txt')
>>> todo.readline()

‘Get groceries\n’

>>> todo.readline()

‘Organize room\n’

>>> todo.readline()

‘Print labels\n’

>>> todo.readline()

‘Write article\n’

>>> todo.readline()

‘Study for exam\n’

>>> todo.readline()

‘Learn to cook’

>>> todo.readline()

>>> todo.readline()

e. Readlines()

Lastly, the readlines() method reads the rest of the lines/file.

>>> todo.seek(0)
>>> todo.read(5)

‘Get g’

>>> todo.readlines()
[‘Groceries\n’, ‘Organize room\n’, ‘Print labels\n’, ‘Write article\n’, ‘Study for exam\n’, ‘Learn to cook’]
Python Interview Questions

6. Python Write to File

To write a Python file, we use the write() method.

>>> todo=open('To do.txt')
>>> todo.write("HI")

Traceback (most recent call last):

File “<pyshell#56>”, line 1, in <module>

todo.write(“HI”)

io.UnsupportedOperation: not writable

Here, we did not open the Python file in a writable format. Let’s open it properly.

>>> todo=open('To do.txt','a')
>>> todo.write('\nLearn to cook')

14

>>> todo.close()

When we checked in the file (refreshed it), we found:
Get groceries
Organize room
Print labels
Write article
Study for exam
Learn to cook
Concluding, you can use ‘w’, ‘a’, or ‘x’. The ‘w’ erases the content and writes over it. So, be careful with it. Also, write() returned 14 here because it appended 14 characters to Python file.
But you can’t read a Python file if you open it in ‘a’ mode.

>>> todo=open('To do.txt','a')
>>> todo.read()

Traceback (most recent call last):

File “<pyshell#13>”, line 1, in <module>

todo.read()

io.UnsupportedOperation: not readable

To get around this, you’d have to use ‘a+r’.

So, this was all about Python File I/O Tutorial. Hope you like our explanation.

7. Conclusion

In this Python file i/o tutorial, we saw a few Python functions and methods like read(), write(), readline(), readlines(), seek(), and tell(). Now, you’re able to manipulate files on a rudimentary level. Go ahead and practice, and come back again tomorrow for more. Furthermore, if you feel any query, feel free to ask in the comment section.
See Also- Range Function & Python Function Arguments
For reference

1 Response

  1. uma says:

    how to compare two csv files and print the same information in one file and print diffent information those files in one file…

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.