Python Read File, Write File, Open File, Delete File, Copy File

Filed Under: Python

In this tutorial we are going to learn about Python File Operations such as python read file, python write file, open file, delete file and copy file. Our previous tutorial was on Python Dictionary. You can find that in this link.

Python File

In the previous tutorial we used console to take input. Now, we will be taking input using file. That means, we will read from and write into files. To do so, we need to maintain some steps. Those are

  1. Open a file
  2. Take input from that file / Write output to that file
  3. Close the file

We will also learn some useful operations such as copy file and delete file.

Why Should We Use File Operation

Suppose, you are trying to solve some problem. But you can’t solve it at once. Also, the input dataset of that problem is huge and you need to test the dataset over and over again. In that case you can use Python File Operation. You can write the dataset in a text file and take input from that text file according to your need over and over again.

Again, if you have to reuse the output of your program, you can save that in a file. Then, after finishing your program, you can analysis the output of that program using another program. In these case you need Python File Operation. There may be some other cases where you may need Python File Operation.

Python Open File

According to the previous discussion, the first step we have to perform in Python File Operation is opening that file. You can open a file by using open() function. This function take two arguments. The first one is file address and the other one is opening mode. There are some mode to open a file. Most common of them are listed below:

  • ‘r’ : This mode indicate that file will be open for reading only
  • ‘w’ : This mode indicate that file will be open for writing only. If file containing containing that name does not exists, it will create a new one
  • ‘a’ : This mode indicate that the output of that program will be append to the previous output of that file
  • ‘r+’ : This mode indicate that file will be open for both reading and writing

Additionally, for Windows operating system you can append ‘b’ for accessing the file in binary. As Windows makes difference between binary file and text file.

Suppose, we place a text file name ‘file.txt’ in the same directory where our code is placed. Now we want to open that file. However, the open(filename, mode) function returns a file object. With that file object you can proceed your further operation.

python open file, python file


#directory:   /home/imtiaz/code.py
text_file = open('file.txt','r')

#Another method using full location
text_file2 = open('/home/imtiaz/file.txt','r')
print('First Method')
print(text_file)

print('Second Method')
print(text_file2)

The output of the following code will be


================== RESTART: /home/imtiaz/code.py ==================
First Method

Second Method

>>> 

Python Read File, Python Write File

There are some methods to read from and write to file. The following list are the common function for read and write in python. Note that, to perform read operation you need to open that file in read mode and for writing into that file, you need to open that in write mode. If you open a file in write mode, the previous data stored into that fill will be erased.

  • read() : This function reads the entire file and returns a string
  • readline() : This function reads lines from that file and returns as a string. It fetch the line n, if it is been called nth time.
  • readlines() : This function returns a list where each element is single line of that file.
  • readlines() : This function returns a list where each element is single line of that file.
  • write() : This function writes a fixed sequence of characters to a file.
  • writelines() : This function writes a list of string.
  • append() : This function append string to the file instead of overwriting the file.

The following code will guide you to read from file using Python File Operation. We take ‘file.txt’ as our input file.


#open the file
text_file = open('/Users/pankaj/abc.txt','r')

#get the list of line
line_list = text_file.readlines();

#for each line from the list, print the line
for line in line_list:
    print(line)

text_file.close() #don't forget to close the file

python read file

Again, the sample code for writing into file is given below.


#open the file
text_file = open('/Users/pankaj/file.txt','w')

#initialize an empty list
word_list= []

#iterate 4 times
for i in range (1, 5):
    print("Please enter data: ")
    line = input() #take input
    word_list.append(line) #append to the list


text_file.writelines(word_list) #write 4 words to the file

text_file.close() #don’t forget to close the file

python write file

Python Copy File

We can use shutil to copy file. Below is an example showing two different methods to copy file.


import shutil

shutil.copy2('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copy2.txt')

#another way to copy file

shutil.copyfile('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copyfile.txt')

print("File Copy Done")

Python Delete File

We can use below code to delete a file in python.


import shutil
import os

#two ways to delete file
shutil.os.remove('/Users/pankaj/abc_copy2.txt')

os.remove('/Users/pankaj/abc_copy2.txt')

Python Close File

As you see in the previous example, we used close() function to close the file. Closing the file is important.

So that’s all for Python File Operation. If you have any query, please feel free to ask that in comment box.

Python FileNotFoundError

You will get this error if the file or directory is not present. A sample stack trace is given below.


  File "/Users/pankaj/Desktop/string1.py", line 2, in <module>
    text_file = open('/Users/pankaj/Desktop/abc.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: '/Users/pankaj/Desktop/abc.txt'

Please check the file path and correct it to get rid of FileNotFoundError.

References:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages