DEV Community

Cover image for File handling in python
Introschool
Introschool

Posted on • Updated on

File handling in python

Subscribe to our Youtube Channel To Learn Free Python Course and More

File Handling in Python

What is File Handling?
The File Handling is the way of performing operation on the file present in your computer system. A file is a named location of data in the computer memory. To perform an operation on the file, first you have to open the file. After getting done with the operations, the file needs to be closed.

Computer stores files in the binary format. There are so many file types like image files, exe files, csv files, but while handling we generally divide files into two categories - text files and binary files. Python gives you option to open the file in both binary and text format. We will see them in detain in the below section.

How to Open a File?
Opening the file is the first step of performing any operation on the file. To open a file, we can use Python’s built-in function open(). The open() function takes the path of the file as an argument. It returns the file object. You can also specify the modes of operations like reading, writing or format of the file like binary or text. See the below code.

Note: If you don’t specify the mode in open function then the default is reading in text mode.

# File Handling
'''
Syntax
open(file_path, mode)
'''
# Opening file for reading in text mode.
file = open('file1.txt')

# Opening file for writing in text mode.
file = open('file1.txt', 'w')
Enter fullscreen mode Exit fullscreen mode

Different Modes of Opening a File
Modes are there to tell the Python interpreter that you opening file for reading or writing. You want to open it in text format or binary format. Let’s see them below in detail.

‘r’
This is default mode. The ‘r’ mode opens a file for reading.
‘t’
This is also default mode. This mode is used to open a file in text format.
‘b’
This mode is used to open a file in binary format.
‘w’
This mode is used to open a file for writing. If the file doesn’t exist then it creates a new file.
‘x’
This mode is used to create and writing to a new file.
‘a’
This mode is used for appending at the end of the file.
‘+’
This mode is used for reading and writing.

Simply -

  • If you want to read the file, use ‘r’
  • If you want to read and write the file, use ‘r+’
  • If you want to overwrite the file, use ‘w’
  • If you want to append to the file, use ‘a’

Read and Write Operations.

You know that how to open a file for reading and writing. Now you will get to know that how to perform reading and writing operation. Python has some built-in function for reading and writing a file. Let’s see them in the below section.
Writing a file
Let’s create a new file called new.txt and add some content to the file.

f = open('new.txt', 'w')

f.write('This is a new file.\n')
f.write('This is the second line.\n')
f.write('This is the last line.\n')

f.close()

Enter fullscreen mode Exit fullscreen mode
  • First we created a new file called ‘new.txt’ using the mode ‘w’. Remember if the file does not exist then it creates the new file.
  • Python’s built-in function write() is used to write a file. To write the string or sequence of bytes(for binary files) write() function is used. The write() function returns the number of characters written to a file.
  • You can see that we used ‘\n’ in the strings. It’s a new line character. If you see the ‘new.txt’, It will look like this
This is a new file.
This is the second line.
This is the last line.
Enter fullscreen mode Exit fullscreen mode
  • In the last we use close() function to close the file. Reading a file

To read a file there are various built-in function like read(n) or readlines(). Let’s read the file that we just created.

f = open('new.txt', 'r')

f.read(6)
# Output: 'This i'



f.read()
# Output: 's a new file.\nThis is the second line.\nThis is the last line.\n'

f.read()
# Output: ''
Enter fullscreen mode Exit fullscreen mode
  • First we open the file in the read mode. We don’t need to specifically the mode for reading because it is default.
  • Python’s built-in function read() is used to read the file. The read(n) function takes a number as an argument and returns the number of characters in the file. If the number is not specified, it reads up to the end of the file.
  • Once the end is reached it returns the empty string.
  • You can use readline() method to read a line in the file. Each time you call this method, it r returns a line from the file.
f = open('new.txt', 'r')

f.readline()
# Output: 'This is a new file.\n'

f.readline()
# Output: 'This is the second line.\n'

f.readline()
# Output: 'This is the last line.\n'
Enter fullscreen mode Exit fullscreen mode
  • You can use readlines() method to get the list of the lines in the file.
  • The tell() method is used to find the file position and seek() method is used to change the cursor position.
f = open('new.txt', 'r')

f.read(6)
# Output: 'This i'



f.read()
# Output: 's a new file.\nThis is the second line.\nThis is the last line.\n'

f.read()
# Output: ''

f.tell()
# Output: 68

f.seek(0)  # bring the cursor to the initial position

f.readline()
# Output: ['This is a new file.\n', 'This is the second line.\n', 'This is the last line.\n']
f.close()
Enter fullscreen mode Exit fullscreen mode
  • We can also use a for loop to read lines of the file.
f = open('new.txt', 'r')

for line in f:
    print(line)

'''
# Output:
This is a new file.

This is the second line.

This is the last line.
'''
Enter fullscreen mode Exit fullscreen mode

How to Close a File?

This is the last step in File handling process. You know that to close a file we use Python’s built-in function close(). This function will only work if there is no error after f.open(...) statement. If there is any error then the Python interpreter will not call f.close() method because it reads the code line by line and on founding any error it stops.

To make sure that the file gets closed whether the error occurs or not, with statement is used. See the below code.

with open('new.txt', 'r+') as f:
    lines = f.readlines()


print(lines)
# Output: 
# ['This is a new file.\n', 'This is the second line.\n', 'This is the last line.\n']
Enter fullscreen mode Exit fullscreen mode

When you use with statement, you don’t need to explicitly use the close() function. The with statement automatically close the file
after getting done with the read and write operations.

Latest comments (0)