How Can We Help?
Python provides the facility of working on Files. A File is an external storage on a hard disk, from where data can be stored and retrieved. Using file handling operation, we can read the data from the file and write the data to the files.
The access mode is the different modes of files in which files can be opened.
In Python, a file can be opened in two modes:
- Text Mode
- Binary Mode
Python supports the following access mode.
Access Modes | Description |
---|---|
r | The “r” access mode opens a file for reading only. The file pointer is placed at the beginning of the file, and this is the default mode. |
w | This mode opens a file for writing only. It overwrites the file if it exists; otherwise, the file object creates a new file for writing. |
rb | The “rb” mode opens a file for reading only in binary format, and then the pointer is placed at the beginning of the file, which is the default mode. |
r+ | The “r+” mode opens a file for both reading and writing. Then the pointer is placed at the beginning of the file. |
rb+ | This mode opens a file for both readings and writing in binary format. Then the pointer is placed at the beginning of the file. |
wb | This mode opens a file for writing only in binary format. It overwrites the file if it exists; otherwise, the file object creates a new file for writing. |
w+ | It opens a file for both writing and reading. It overwrites the existing file if it exists; otherwise, the file object creates a new file for reading and writing. |
Access Modes | Description |
---|---|
wb+ | It opens a file for both writing and reading in binary format. It overwrites the existing file if it exists; otherwise, the file object creates a new file for reading and writing. |
a | It opens a file for appending in the append mode. The file pointer is placed at the end of the file if the file exists; otherwise, the file object creates a new file for writing. |
ab | It opens a file for appending in binary format in the append mode. The file pointer is placed at the end of the file if the file exists; otherwise, the file object creates a new file for writing. |
a+ | The “a+” opens a file for both appending and reading in the append mode. The file pointer is placed at the end of the file if the file exists; otherwise, the file object creates a new file for reading and writing. |
ab+ | The “ab+” opens a file for both appending and reading in binary format in the append mode. The pointer is placed at the end of the file if the file exists; otherwise, the object creates a new file for reading and writing. |
Operation on Files in Python
Python supports the following operations on files.
Sr. | Operation | Function | Description |
---|---|---|---|
1 | Opening a File | open() | Used to open any file. |
2 | Closing a File | close() | Used to close an opened file. |
3 | Writing to a File | write() | Used to write into an existing or new file. |
4 | Reading from a File | read() | Used to read data of an existing file. |
2.1) Opening a File:
- We use the open() built-in Python function to open a file.
- It returns an object of a file, which is used with other functions.
- We can perform read, write, etc. operations on the opened file
- Syntax:
obj=open(filename , mode , buffering)
- filename: It is the file name we want to access.
- mode: It specifies the mode in which the file is to be opened. There are many types of modes. Mode depends on the operation to be performed on a file. The default access mode is read (r)
- buffering: It is a temporary space.
- If the buffering value is set to 0, no buffering takes place.
- Line buffering is performed while accessing a file if the buffering value is set to 1.
- If we specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size.
- If we specify the buffering value as a negative, then the buffer size is the system’s default.
- E.g., 1: Open a “pythontest.text” file in write mode at C:\Users\Desktop. Presently “pythontest.txt” file does not exist on “C:\Users\Desktop“, so first, we need to create it. So we need to open it in write mode as below. To open a text file at “C:\Users\Desktop“, first create an “example.py” file at “C:\Users\Desktop” and write a code as below in it.
Example (1)
file_open =open("pythontest.txt","w")
print("Opened file name: ",file_open)
Output:
After running the “example.py” file, the output shows as below with the file name and access mode name in the python shell, and one “pythontest.txt” file would be created on the desktop because we have an open file in write mode.
Opened file name: \<_io.TextIOWrapper name=’pythontest.txt’ mode=’w’ encoding=’cp1252′>
- E.g., 2: Let’s open an existing “pythontest.text” file in read mode, which is placed at
“C:\Users\Desktop“. Here, we will use the same file as “example.py” and write the input code as below in it.
Example (2)
file_open =open("pythontest.txt","r")
print("Opened file name: ",file_open)
Output:
After running the “example.py” file, the output is shown below with the file name and access mode name.
Opened file name: \<_io.TextIOWrapper name=’pythontest.txt’ mode=’r’ encoding=’cp1252′>
Note: Here, the file is opened by the machine virtually, so we can’t see it.
- E.g., 3: Let’s open an existing “pythontest.text” file in read mode with its full address. Here, we will use the python shell to write the input code as below in it and use the “file_object.name ” method to know the file’s path.
Example (3)
>>> file_open =open("C://Users//Desktop//pythontest.txt","r")
>>> print("An opened file name with path: ", file_open.name)
Output:
An opened file name with path: “C://Users//Saurav//Desktop//pythontest.txt“
2.2) Closing a File:
- We use the close() python built-in function to close a file.
- Once we are finished with the operations on an opened file, then at the end, we need to close the file. It is done by the close().
- This function prevents the file from being corrupted.
Syntax:
fileobject.close()
- E.g., 1: Let’s close an existing “pythontest.text” file in read mode, which is placed at “C:\Users\Desktop“. Here, we will use the same file as “example.py” and write the input code as below in it.
Example (4)
file_open =open("pythontest.txt","r")
print("Opened file name: ",file_open)
file_open.close()
Output:
After running the “example.py” file, the output shown below with the file name and machine will virtually close the file.
- E.g., 2: Let’s open a random text file in read mode with its complete address by using user input and then close it. Here, we will use the python shell to write the input code below and the function as main() and “file_object.name” method to know the file’s path.
Example (5)
>>> def main():
file_name=input("Enter filename: ")
input_file=open(file_name,'r')
print("Input file name: ",input_file.name)
input_file.close()
>>> main()
Enter filename: C:\Users\Saurav\Desktop\pythontest.txt
Output:
Input file name: C:\Users\Saurav\Desktop\pythontest.txt
2.3)Writing to a file in Python
- We use the write() Python built-in function to write a string into the file.
- The write() method does not add a newline character (‘\n‘) to the end of the string.
- Note: Python strings have binary data and text data. We can write both kinds of data by using writing access mode as “wb” and “w” respectively.
Syntax:
fileobject.write(string)
- E.g., 1: Let’s write a sentence as “Welcome Python!!” and in the following line as “Python is an easy language.” in an existing “pythontest.text” file in write mode, which is placed at “C:\Users\Desktop“. Here, we will use the same file as “example.py” and write the input code as below in it.
Example (6)
file_open =open("pythontest.txt","w")
file_open.write("Welcome Python!!\n")
file_open.write("Python is a easy language.")
file_open.close()
Output:
After running the “example.py” file, sentences such as “Welcome Python!! and Python is an easy language.” are written in the “pythontest.txt” file as below. Here, the escape character “\n” is used to write the following sentence in the following line.
- Note: We can also write the variable value in the file.
- E.g., 2: Let’s write a variable value as “Anybody can learn python.” in the above-created file as “pythontest.txt“. Here, we will use the same as “example.py” and modify the input code as below in it.
Example (7)
file_open =open("pythontest.txt","w")
sentence= "Anybody can learn python."
file_open.write("Welcome Python!!\n")
file_open.write("Python is a easy language.")
file_open.write(sentence)
file_open.close()
Output:
After running the “example.py” file, the variable value “Anybody can learn python.” is written in the “pythontest.txt” file as below.
Note: In write(w) mode, The file pointer is always placed at the beginning of the file. To place the pointer at the end of the file, we need to open the file in append mode.
- E.g., 3: Let’s write a variable value as “Python is a current market language” with all existing sentences of the above-created file as “pythontest.txt“. Here, we will use the same file as “example.py” and modify the input code as below in it.
Example (8)
file_open =open("pythontest.txt","a")
sentence= " \nPython is a current market language."
file_open.write(sentence)
file_open.close()
Output:
After running the “example.py” file, the variable value “Python is a current market language” is added at the end of all previous lines in the “pythontest.txt” file as below, and the file pointer is placed at the end of the file.
2.4)Reading from a File in Python
- We use the read() Python built-in function to read a string from the file.
- Note: We can read binary and text data by reading access modes as “rb” and “r” respectively.
Syntax:
fileobject.read(value)
Where value is the number of bytes to be read, if no value is given in the read() function, then the program reads until the end of the file.
- E.g., 1: Let’s read the entire content of an existing “pythontest.txt” file in reading (r) access mode. Here, we will use the same file as “example.py” and modify the input code as below in it. We have opened the file in reading mode and used the “read_line” variable to show the result of reading lines in the print statement.
Example (9)
file_open =open("pythontest.txt","r")
read_line=file_open.read()
print("Data of the file: ",read_line)
file_open.close()
Output:
After running the “example.py” file, the variable “read_line” reads all the lines of the “pythontest.txt” file and shows the result as below.
- E.g., 2: Let’s read the first line of an existing “pythontest.txt” file. Here, we will use the same file as “example.py” and add the value = 16 in the read() function as below.
Example (10)
file_open =open("pythontest.txt","r")
read_line=file_open.read(16)
print("First line of the file: ",read_line)
file_open.close()
Output:
After running the “example.py” file, the variable as read_line reads the first line of the “pythontest.txt” file, which includes 16 bytes (16 characters) and shows the result as below.
2.4.1) File Reading Methods:
Python supports the following file-reading methods.
Method | Syntax | Description |
---|---|---|
readline() | \<fileobj>.readline() | It returns the following line of the file. This is all the text up to the end and includes the next newline character. |
readlines() | \<fileobj>.readlines() | It returns a list of the remaining lines in the file. Each list item is a single line, including the newline characters |
- E.g., 1: Let’s read all the data of the existing “pythontest.txt” file using the readline() method. Here, we will use the same file as “example.py” and add the code of the readline() function as below.
Example (11)
file_open =open("pythontest.txt","r")
for i in range(4):
read_line = file_open.readline()
print(read_line)
file_open.close()
Output:
After running the “example.py” file, the output shows all file lines as below.
- E.g., 2: Let’s read only 10 characters of the first two lines of the existing “pythontest.txt” file using the readline() method. Here, we will use the same file as “example.py” and add the value =10 at the readline() function as below.
Example (12)
file_open =open("pythontest.txt","r")
for i in range(4):
read_line = file_open.readline(10)
print(read_line)
file_open.close()
Output:
After running the “example.py” file, the output shows the first 10 characters of the first two lines of the file in two different lines, as below.
- E.g., 2: Let’s modify the data of the existing “pythontest.txt” file as below and then do the followings.
- Read the data of the file by using the readlines() method.
- Create a username from the data of an existing file
- Print the created username in the output.txt file. Here, we will use the same file as “example.py” and add the readlines() function code below to read the file’s data.
Example (13)
Input_File =open("pythontest.txt","r")
Output_File =open("output.txt","w")
for i in Input_File.readlines():
first,middle,last=i.split()
username=first[0].lower()+last[:3].upper()+middle[:2]
print(username, file=Output_File)
Input_File.close()
Output_File.close()
In the above code, we split the 3 words of each line by space as first, middle, and last. Then, we took the substrings of every word and used the lower() and upper() method to change the case of substring characters. Then added all resulting substring characters to create a username and printed the result in the username in the output file. This process is done for each line of the file.
Creation of a username for the first line:
First input line: "Welcome Python Language!!"
Then, First word="Welcome" so first[0]= "W"
Second word = "Python" so middle[:2]="Py"
Third word="Language" so last[:3]="Lan"
Then use upper() and lower() method, first[0].lower() = "w"
last[:3].upper()="LAN"
middle[:2]="Py"
Then combined all as a username= first[0].lower()+last[:3].upper()+middle[:2]
="wLANPy"
Output:
After running the “example.py” file, An “output.txt” file would be created at “C:\Users\Desktop” with username details as below.
3) Attributes of File:
The attributes of the file show the detail of the file, like whether the file is closed or not, its access mode, its name, etc. Python supports the following file attributes.
Attributes | Description |
---|---|
\<fileobj>.closed | It returns true if the file is closed; otherwise, false. |
\<fileobj>.mode | It returns the access mode in which the file is being opened. |
\<fileobj>.name | It returns the name of the file. |
- E.g., Let’s use file attributes to know the detail of opened file. Here, we will use the same file as “example.py” and modify the code as below.
Example (14)
File_open =open("pythontest.txt","r")
print("Filename:",File_open.name)
print("Is file closed? ",File_open.closed)
print("Access mode of file: ", File_open.mode)
Output:
After running the “example.py” file, the output shows the result of the file attributes like opened file name, False because the file is already opened, and access mode of the file as “read mode“.
4) Python File Handling Methods
Python supports the following file-handling methods.
Method | Description |
---|---|
remove() | It is used to delete an existing file. |
rename() | It is used to rename an existing file. |
tell() | It is used to get the exact position of the pointer in the file. |
seek() | It is used to change the current file position |
4.1) remove():
It deletes an existing file.
It takes one argument as a file name to be deleted.
To use this method, we must import the “os” module of Python.
Syntax
os.remove(file_name)
E.g., Let’s remove the existing file “output.txt“. Assume the “output.txt” file is located at “C:\Users\Desktop“.
Here, we will use the same file as “example.py” and modify the code as below.
Example (15)
import os
os.remove("output.txt")
Output:
In the output, the file name “output.txt” will be deleted from location “C:\Users\Desktop“.
4.2) rename():
It renames an existing file.
It takes two arguments, existing_file_name and new_file_name.
To use this method, we must import the “os” module of Python.
Syntax:
os.rename(existing_file_name, new_file_name)
E.g., Let’s change the existing file’s name to “pythontest.txt ” with “newpython.txt“. Assume the “pythontest.txt” file is located at “C:\Users\Desktop“.
Here, we will use the same file as “example.py” and modify the code as below.
Example (16)
import os
os.rename("pythontest.txt","newpython.txt")
Output:
In the output, the file name “pythontest.txt” was changed to “newpython.txt” and the changed file is located at “C:\Users\Desktop“.
Old file:
New file:
4.3) tell():
It gives the exact position of the pointer in the file.
It takes one argument as existing_file_name.
Syntax:
<file_obj>.tell() , where file_obj = File name for which we want to know the file pointer details
E.g., Let’s read the 10 bytes of the first line of the existing file as “pythontest.txt” and shows the last position of a file pointer. Assume the “pythontest.txt” file is located at “C:\Users\Desktop”.
Here, we will use the same file as “example.py” and modify the code as below.
Example (17)
File_open=open("pythontest.txt","r")
read_line=File_open.read(10)
print("Read file: ", read_line)
position=File_open.tell()
print("Current file position: ", position)
File_open.close()
Output:
In the output, the file pointer position is at 10 because we read the 10 bytes of the first line of the “pythontest.txt” file using the read() method. The 10 bytes of the first line is “Welcome Py“.
4.4) seek():
It changes the current file position.
Syntax:
seek(offset[, from])
Here, offset = It indicates the number of bytes to be moved.
from = It specifies the reference position from where the bytes are to be moved.
If from is set to “0”, it means to use the beginning of the file as the reference
position, and set to “1”, it means to use the current position as the reference position, and
set to “2”, it means to use the end of the file as the reference position.
E.g., Let’s read the 10 bytes of the first line of the existing file as “pythontest.txt” and then again read the 12 bytes of the same line by using seek() current position function. Assume the “pythontest.txt” file is located at “C:\Users\Desktop“.
Here, we will use the same file as “example.py” and modify the code as below.
Example (18)
File_open=open("pythontest.txt","r")
read_line1=File_open.read(10)
print("Read 10 bytes of file: ", read_line1)
position= File_open.seek(0,1)
read_line_again=File_open.read(12)
print("read line against seek position: ",read_line_again)
File_open.close()
In the above code, we read the first 10 bytes of the first line as “Welcome Python Language!!” and then use seek(0,1) function to change the file pointer position from 0 to the current position and then again read a byte of the same line.
Output:
In the output, the first 10 bytes are “Welcome Py” and after using seek(0,1) means seek() current position function, the file pointer starts from the current position, which is byte 10. So, after reading 12 bytes, the output shows the 12 bytes after the first 10 bytes as “thon Language”.