Python - File Handling
File-handling is an essential part of programming. Python has several functions for file handling such as creating, opening, reading, updating and deleting files.
Open File
The Python open() function is used to open a file and returns it as a file object. It takes two parameters - filename and mode. See the syntax below:
Syntax
open(filename, mode)
Parameters
filename |
Required. specify filename with path which need to be opened. |
mode |
Optional. specify mode of opening the file. default is read mode for text file that is "rt". |
The different modes of opening a file are mentioned below:
Mode | Description |
---|---|
r | Default value. Opens a file for reading only. Raise an exception if the file does not exist. |
r+ | Opens a file for reading and writing. Raise an exception if the file does not exist. |
w | Opens a file for writing only. Creates the file if it does not exist. |
w+ | Opens a file for reading and writing. Creates the file if it does not exist. |
a | Opens a file for appending only. Creates the file if it does not exist. |
a+ | Opens a file for appending and reading. Creates the file if it does not exist. |
x | Creates the specified file. Raise an exception if the file already exists. |
x+ | Creates the specified file and Opens the file in reading and writing mode. Raise an exception if the file already exists. |
Apart from this, the file can be handled as binary or text mode
Mode | Description |
---|---|
t | Default value. Opens a file in the text mode. |
b | Opens a file in the binary mode. |
In the example below, open() function is used to open the file called python_test.txt in "rt" mode which means read text mode. The "rt" mode is also the default mode hence it does not require to specify.
MyFile = open("python_test.txt", "rt") # is equivalent to MyFile = open("python_test.txt")
Read File
The open() function returns a file object which has read() method to read the content of the file object. Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
The below program can be used to read the whole content of test.txt.
MyFile = open("python_test.txt", "r") print(MyFile.read())
The output of the above code will be:
This is a test file. It contains dummy content.
Read a part of file
The Python read() method has an optional parameter which is used to specify number of bytes to read and return of the file object. In the example below, read() method is used to read the partial content of the file called MyFile.
MyFile = open("python_test.txt", "r") #read first 10 bytes of the content print(MyFile.read(10)) #read next 10 bytes of the content print(MyFile.read(10))
The output of the above code will be:
This is a test file.
Read Lines
The Python file object has readline() method which is used to read and return one line of the file. If the method is called multiple times, it will read and return multiple lines of the file. In the example below, readline() method is used twice to read first two lines of the file called MyFile.
MyFile = open("python_test.txt", "r") #read first line of the content print(MyFile.readline()) #read second line of the content print(MyFile.readline())
The output of the above code will be:
This is a test file. It contains dummy content.
Loop through the lines of the File
By using for loop, the whole content of the file can be read line by line.
MyFile = open("python_test.txt", "r") for line in MyFile: print(line)
The output of the above code will be:
This is a test file. It contains dummy content.
Similarly, the while loop can also be used to read the whole content of the file line by line.
MyFile = open("python_test.txt", "r") line = MyFile.readline() while line: print(line) line = MyFile.readline()
The output of the above code will be:
This is a test file. It contains dummy content.
Close File
The Python file object has close() method which is used to close the specified open file. In the example below, Python file close() method is used to close an opened file called MyFile.
MyFile = open("python_test.txt", "r") #read content before closing the file print(MyFile.read()) MyFile.close() #read content after closing the file print(MyFile.read())
The output of the above code will be:
This is a test file. It contains dummy content. ValueError: I/O operation on closed file.
Write to an Existing File
The Python file object has write() method which is used to write content in the specified open file. To write content in the file, two file open() modes can be used.
- "a" - append mode. to append to the end of the file.
- "w" - write mode. to overwrite any existing content of the file.
The example below explains how to write content in a given file in append and write mode.
#append content to the file MyFile = open("python_test.txt", "a") MyFile.write("add more content.") MyFile.close() #overwrite existing content of the file MyFile = open("python_test.txt", "w") MyFile.write("add more content.") MyFile.close()
Create a New File
To create a new file, the file open() function can be used in following modes:
- "a" - append mode. Opens a file in append mode and creates the file if it does not exist.
- "w" - write mode. Opens a file in write mode and creates the file if it does not exist.
- "x" - create mode. Creates a file and raises exception if it already exists.
The example below explains how to create a new file called NewFile if it does not exist using append, write and create mode.
#Creates a file "MyFile" if it does not exist MyFile = open("python_test.txt", "a") #Creates a file "MyFile" if it does not exist MyFile = open("python_test.txt", "w") #Creates a file "MyFile" if it does not exist MyFile = open("python_test.txt", "x")
Delete a File
To delete a file, os module must be imported in the current session. The os module contains remove() function which is used for deleting the specified file. In the example below, os.remove() function is used to delete the file called MyFile.
import os os.remove("python_test.txt")
Check if File exist
To check whether a file exists or not, the os module contains path.exists() function which can be used to check it.
import os if os.path.exists("python_test.txt"): os.remove("python_test.txt") else: print("The file does not exist")
Delete Folder
The os module contains rmdir() function which can be used to delete an entire folder.
import os os.rmdir("myfolder")