Python File Operations - Read, Write and Close Files in Python

Here, you will learn about Python file operations, opening files, closing files, reading files, writing to files and python file methods....

Welcome to another interesting article on Python Programming Language. Here, you will learn about Python file operations, opening files, closing files, reading files, writing to files and python file methods. 

Python file operations, opening files, closing files, reading files, writing to files and python file methods

Python File Handling

Files are named location on a disk to store data permanently for future use. To store data on non-volatile memory i.e., hard disk permanently for future purposes, files are used by the programmers.

File handling is plays an important role in web applications. It allows users to handle files i.e., open, write, read or close files, etc. When we need to store any data permanently in the files then file handling plays an important role. File handling allows us to open a file to read and write to it and close the file after we are done. Python also provides us the file handling function to handle files. In python, the files are treated in two ways i.e., binary and text. The file operation in python takes place in following manner;

• Opening files

• Reading or Writing 

• Closing files

Opening Python Files

In python, with built-in open() function, we can to open a file. The open() function accepts two arguments i.e., name of the file (filename) and mode in which file will be accessed (mode). Then the open function returns a file object in which we can perform several operations like reading or writing etc.

Syntax

f = open(filename, mode)

We can access a python file using various types of modes like append, read, write, etc. The types of access modes to open a file are explained in detail in the following table;

Mode Description
a To open a file for appending.
b To open a python file in binary mode.
r To open a python file for reading.
t To open a python file in text mode.
w To open a python file for writing.
x To open a python file for exclusive creation.
r+ To open a python file for both reading and writing (updating).
# a file named with "main", will be opened with the reading mode.

file = open('main.txt', 'r')

# This will print every line one by one in the file

for each in file:

    print(each)

Writing to Python Files

Python file handling also allows us to write to a file. So to write to a file in python, we have to open the file in append or write mode. These modes are explained as follows;

write mode

This mode is used when we want to open a file for writing. But we have to use it very carefully as it overwrites the file if any file already exists. In this mode, the pointer is at the starting of the python file. This mode also creates a new file if it doesn't exists.

# Python code to create a file

file = open('main.txt','w')

file.write("This is the write command")

file.close()

append mode

This mode is used when we want to open a file for appending. And unlike write mode, it doesn't overwrite the existing files. In this mode, the pointer is at the ending of the python file. And This mode also creates a new file if it doesn't exists.

# Python code to illustrate append() mode

file = open('main.txt','a')

file.write("This will add this line")

file.close()

Reading Python Files

We have to open the python scripts or files in read mode in order to read it. Python provides various methods by which we can read a file and these methods are explained as follows;

read() method

To read a whole file at a time, we use the read() python built-in function. For newline, this method returns . And reaching the end of the file, we get a whole empty string for reading further. To do it, we have to change the cursor position of the current file by using seek() and tell() function.

# Python code to illustrate read() method

file = open('main.txt', 'r'

print file.read()  

readline() method

The readline() method is used to read a particular line of the python file at a time until the newline characters is found. In this method, /n is added at the end of the line.

# Python code to illustrate readline() method

file = open('abc.txt', 'r'

print file.readline() 

readlines() method

The readlines() method is used to read a whole python file line by line.

# Python code to illustrate readlines() method

file = open('abc.txt', 'r'

print file.readlines()   

read(n) method

The read(n) function is used to read specified count of characters in the python file.

# Python code to illustrate read(n) method

File = open('abc.txt','r'

print read(5)

for loop method

for loop is an alternative for readlines() method. By using for loop, we can read a whole python file line by line.

# Python code to illustrate for loop method

file = open('main.txt','r');

#running a for loop     

for i in file:    

    print(i) 

Closing Python Files

Here we will discuss about operation on closed file python or python i/o operation on closed file in detail;

The close() function

When we are done with performing all operations in a file, we need to close the python file to free up the tied resources with the that file. So, it is done with the help of python built-in close() function.

Syntax

file.close()

Example:

file = open('main.txt', 'a'

file.write('append the text'

file.close()

The try...finally block

Using close() method is not fully safe. Sometimes when any exception occurs while performing any operation in python file, the code terminates without closing the file. So there is a more safer way to close the file that is using try...finally block.

try

file = open('main.txt','w'

finally:

file.close()

The with statement

Another best way to close a python file after performing all operations is using the with statement which is introduced in the python 2.5. Using with statement ensures to close the python file when the nested block exists inside the with statement. If we use with statement then there is no need to call the close() method explicitly and it prevents files from corrupting.

Syntax

with open('main.txt', 'r') as file:  

Example:

with open('main.txt', 'r') as file:    

    content = file.read();   

    print(content)    

Deleting a File

In python, we can delete a file by using the remove() method but for this we have to import the os module to the program.

import os;
os.remove("main.txt")

Python File Methods

The following table contains the list of all python file methods;

Method Description
read() To return the content of the file for reading.
write() To write a particular string to the file.
readable() Checks whether the stream of file is readable or not.
writable() Checks whether the file is writable or not.
readline() To return a particular line of the file.
readlines() To return a list of lines of the file.
writelines() To write a list of string in the file.
close() To close a file.
seek() To change the position of a file.
tell() To return the position of current file.
seekable() Checks whether the position of the file is changeable or not.
truncate() To change the size of a file to a specific size.
isatty() Checks whether the stream of the file is interactive or not.
detach() To detach the raw stream from the buffer.
flush() To flush internal buffer.
fileno() To return file integer number.

Conclusion

Above we have discussed about Python file operations, opening files, closing files, reading files, writing to files and python file methods. Files are named location on a disk to store data permanently for future use. In python, with built-in open() function, we can to open a file. To write to a file in python, we have to open the file in append or write mode. To read a whole file at a time, we use the read() python built-in function. When we are done with performing all operations in a file, we need to close the python file by using close() method.