File-handling is an essential part of programming. Python has several functions for file handling such as creating, opening, reading, updating and deleting files.
The Python open() function is used to open a file and returns it as a file object. It takes two parameters - filename and mode. Please see the syntax below:
open(filename, mode)
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 below example, 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")
The open() function returns a file object which has read() method to read the content of the file object. In the below example, read() method is used to read the whole content of the file called MyFile.
MyFile = open("python_test.txt", "r") print(MyFile.read())
Python is a programming language. Learning Python is fun.
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 below example, read() method is used to read the partial content of the file called MyFile.
MyFile = open("python_test.txt", "r") #read first 33 bytes of the content print(MyFile.read(33)) #read next 10 bytes of the content print(MyFile.read(10))
Python is a programming language. Learning
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 below example, 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())
Python is a programming language. Learning Python is fun.
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)
Python is a programming language. Learning Python is fun.
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()
Python is a programming language. Learning Python is fun.
The Python file object has close() method which is used to close the specified open file. In the below example, 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())
Python is a programming language. Learning Python is fun. ValueError: I/O operation on closed 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.
The below example 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()
To create a new file, the file open() function can be used in following modes:
The below example 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")
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 below example, os.remove() function is used to delete the file called MyFile.
import os os.remove("python_test.txt")
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")
The os module contains rmdir() function which can be used to delete an entire folder.
import os os.rmdir("myfolder")
Methods | Description |
---|---|
Closes the file | |
Next Page | Returns the separated raw stream from the buffer |
Returns a number that represents the stream, from the operating systems perspective | |
Flushes the internal buffer | |
File-handling is an essential part of programming. Python has several functions for file handling such as creating, opening, reading, updating and deleting files. | Returns whether the file stream is interactive or not |
Returns the file content | |
Open File | Returns whether the file stream can be read or not |
Returns one line from the file | |
The Python | Returns a list of lines from the file |
open() | Change the file position |
function is used to open a file and returns it as a file object. It takes two parameters - | Returns whether the file allows us to change the file position |
filename | Returns the current file position |
and | Resizes the file to a specified size |
mode | Returns whether the file can be written to or not |
. Please see the syntax below: | Writes the specified string to the file |
Writes a list of strings to the file |