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

Free Python courses with 57 real-time projects - Learn Python

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

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

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

Output

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

>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.listdir()

Output

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

Output

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

Output

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

Python File I/O - Python Open File

Python File I/O – Python Open File

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

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

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

Output

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.

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

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

Output

BeforeTraceback (most recent call last):

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

print(1/0)

ZeroDivisionError: division by zero

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

Output

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

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

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

Output

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

Output

‘Get g’

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

>>> todo.read()

Output

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

Output

>> todo.close()

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

Output

‘Get g’

>>> todo.tell()

Output

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

Output

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

3. 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='')

Output

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)

Output

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

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

Output

‘Get groceries\n’

>>> todo.readline()

Output

‘Organize room\n’

>>> todo.readline()

Output

‘Print labels\n’

>>> todo.readline()

Output

‘Write article\n’

>>> todo.readline()

Output

‘Study for exam\n’

>>> todo.readline()

Output

‘Learn to cook’

>>> todo.readline()

Output

>>> todo.readline()

Output

5. Readlines()

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

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

Output

‘Get g’

>>> todo.readlines()

Output

[‘Groceries\n’, ‘Organize room\n’, ‘Print labels\n’, ‘Write article\n’, ‘Study for exam\n’, ‘Learn to cook’]

Python Write to File

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

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

Output

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

Output

14
>>> todo.close()

Output

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

Output

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.

Python Interview Questions on File I/O

  1. What is file i/o in Python?
  2. How to use file i/o in Python?
  3. How does file i/o work in Python?
  4. How do you write output to a file in Python?
  5. Why do we need files in Python?

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.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

2 Responses

  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…

    • DataFlair says:

      Here is the code first file is “”first.csv””, second is “”second.csv””. File containing matching and different text is match.csv and diff.csv

      with open(‘first.csv’, ‘r’) as t1, open(‘second.csv’, ‘r’) as t2:
      fileone = t1.readlines()
      filetwo = t2.readlines()

      with open(‘diff.csv’, ‘w’) as outFile:
      for line in filetwo:
      if line not in fileone:
      outFile.write(line)

      with open(‘match.csv’, ‘w’) as outFile:
      for line in filetwo:
      if line in fileone:
      outFile.write(line)

Leave a Reply

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