The perfect place for easy learning...

Python

×

Topics List


Python File Handling





The Python programming language provides built-in functions to perform operations on files. In Python, we may perform the following operations on files.

  • Opening a file
  • Reading from a file
  • Writing into a file
  • Closing a file
  • Creating a file

Let's look at each operation in detail.

Opening a file

In Python, we use the built-in function open( ). This function requires two parameters, the first one is a file name with extension, and the second parameter is the mode of opening. The built-in function open( ) returns a file object. We use the following syntax to open a file.

Syntax

file = open("file_name.extension", "mode")

The Python programming language has four modes to open a file. The following table describes each mode.

File open mode Description
r READ - Opens a file in reading mode. If the file not found it raises an error.
a APPEND - Opens a file in append mode. If the file not exists it creates a new file
w WRITE - Opens a file in writing mode. If the file is not found creates a new file.
x CREATE - Creates a new file. If the file already exists it raises an error.

All the above four modes can be used in combination with "t" or "b" to specify either a text file or a binary file. Let's look at the following statements.

Example
f = open("Sample.txt", "rt")

The above statement opens the Sample.txt file in reading mode. If the file does not exist it generates an error.

Example
f = open("apple.jpg", "rb")

The above statement opens the apple.jpg image file in reading mode. If the file does not exist it generates an error.

The default mode of file open is r and rt.


Reading from a file

The Python has the following built-in functions to read data from a file. To perform the reading operation the file must be opened in reading mode.

  • read( )
  • readline( )

read( ) method

The read() method of file object reads whole data from the open file. But, optionally we can also specify the number of characters to be read.

Let's consider the following text file, Sample.txt

Python File Handling

The read( ) method reads the whole content of the file from the current position of the cursor.

The read(10) method reads the first 10 characters (including white spaces) from the current position of the cursor.


Example
fPtr = open('Sample.txt', 'r')

print('The first 5 characters of Sample.txt are: ')
print(fPtr.read(5))

print('The remaining content of Sample.txt is:\n')
print(fPtr.read())

When we run the above example code, it produces the following output.

Python File Handling

readline( ) method

The readline( ) method of file object reads all the characters from the current cursor position to till the end of the line. But, optionally we can also specify the number of characters to be read.

The readline( ) method reads all the characters from the current position of the cursor to end of the line.

The readline(10) method reads 10 characters (including white spaces) from the current position of the cursor or till the end of the line.


Example
fPtr = open('Sample.txt', 'r')

print('Line_1 of Sample.txt is: ')
print(fPtr.readline())

print('Line_2 first 12 characters of Sample.txt are: ')
print(fPtr.readline(12))

print('\nLine_2 remaining characters of Sample.txt are: ')
print(fPtr.readline())

When we run the above example code, it produces the following output.

Python regular expressions

Writing into a file

To perform write operation into a file, the file must be opened in either 'w' mode (WRITE) or 'a' mode (APPEND). The Python provides a built-in method write( ) to write into the file.

The 'w' mode overwrites any existing content from the current position of the cursor. If the specified file does not exist, it creates a new file and inserts from the beginning.

The 'a' mode insert the data next from the last character in the file. If the file does not exist, it creates a new file and inserts from the beginning.


Example for Append mode
fPtr = open('Sample.txt', 'a')

fPtr.write("This new content has appended!")
fPtr.close()

fPtr = open('Sample.txt', 'r')
print('The updated content of Sample.txt is: ')
print(fPtr.read())
fPtr.close()

When we run the above example code, it produces the following output.

Python regular expressions

Example for Write mode
fPtr = open('Sample.txt', 'w')

fPtr.write("This new content overwrite the existing ")
fPtr.close()

fPtr = open('Sample.txt', 'r')
print('The updated content of Sample.txt is: ')
print(fPtr.read())
fPtr.close()

When we run the above example code, it produces the following output.

Python regular expressions

Closing a file

The Python has a built-in method close( ) of the file object to close the file. We use the following statement to close the above-opened file Sample.txt.


Example
fPtr.close()

Creating a new file

Use the following modes in the open( ) method to create a new file.

  • 'x' mode, creates a specified new file, raises an error if the file already exists.
  • 'a' mode, creates a specified new file if the file does not exist.
  • 'w' mode, creates a specified new file if the file does not exist.

Example for 'x'mode
fPtr = open('NewFile.txt', 'x')

The 'x' mode creates the new file and opens it in 'w' mode so that we can directly write into the file.


Example for 'x'mode
fPtr = open('Sample_1.txt', 'x')

fPtr.write("New file has created!")
fPtr.close()

fPtr = open('Sample_1.txt', 'r')
print('The content of Sample_1.txt is: ')
print(fPtr.read())
fPtr.close()

When we run the above example code, it produces the following output.

Python regular expressions


Your ads here