Python File Handling
A key component of any application is file handling.
There are various functions in Python to create, read, update, and delete files.
Python open() Method
The open()
function is the main function to work with files.
Two parameters of Open()
function: filename, and mode.
There are four possible ways to opening a file :
"r"
- Read - Value default. Opens a reading file if the file doesn't exist error"a"
- Append - Opens an append file, creates a file if it's not available."w"
- Write - Open a writing file, creates the file if there is no file."x"
- Create - Create the file, return the error when the file exists.
Moreover, you can indicate whether the binary or text file should be treated.
"t"
- text - Value of default. Mode Text"b"
- binary mode "b" (e.g. images)
Syntax
To open a read file, the name of the file is sufficient :
f = open("demofile.txt")
The code above is the same as :
f = open("demofile.txt", "rt")
You do not need to mention them because "r"
for reading and "t"
for text are default.
Note : Ensure that the file is available otherwise you'll get an error.
Python Close File - close() Method
When you finish it, it is a recommended practice that you always close the file.
Example :- Close the file when you are finish with it :
f = open("demofile.txt", "r")
# Write code to read data or write data
f.close()
Note : in some circumstances, changes to a file may not appear until you have closed the file, because of the buffering.
Python Read File Content - read() Method
The read()
function is used to read all contents at once or read first
'N' number of characters from a file.
Suppose that we have the file in the same folder as Python : demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
Use the built-in open()
function to open the file.
Example 1 :- Reading all contents at a time from "demofile.txt":
f = open("demofile.txt", "r")
print(f.read())
f.close()
Output :-
This file is for testing purposes.
Good Luck!
When the file is located at another location, the path to the file must be set as follows :
Read Only Parts of the File
The read()
method provides the complete text by default, however you can specify
how many characters you would like to return :
Example 2:- Return the first 5 characters of the file :
f = open("demofile.txt", "r")
print(f.read(5))
f.close()
Output :-
Related Links
Python Read File Contents Line By Line - readline() Method
The readline()
method is used to read a single line from a file.
Example 1 :- Read one line of the file :
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Output :-
You can read the first two lines by executing readline()
twice :
Example 2 :- Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
f.close()
Output :-
This file is for testing purposes.
Example 3 :- Read all lines - Loop through the file line by line :
You may read the entire file, line by line, by looping through file lines :
f = open("demofile.txt", "r")
for x in f:
print(x)
f.close()
Output :-
This file is for testing purposes.
Good Luck!
Python File Write
You can create a new file or refer to an existing file using open()
method in python.
The write()
method is used to write data to a specified file.
You can specify the write mode (append or overwrite) of a file using file mode attributes.
Create File and Write Data to an Existing File
You must provide a parameter in the open()
function to write to an existing file :
"a"
- Append - is to be added to the file end."w"
- Write - will overwrite any content already present.
Note: Both parameters will create a file (if does not exist) and then write or append data to the file.
Suppose that we have the file called myfile.txt and it has following contents:
Welcome To
Python
Example 1 :- Open the "myfile.txt" file and add or append the file contents :
f = open("e:\\myfile.txt", "a")
f.write("File Handling")
f.close()
#open and read the file after the appending:
f = open("e:\\myfile.txt", "r")
print(f.read())
f.close()
Output :-
Python
File Handling
Example 2 :- Open the "myfile.txt" file and override the contents :
f = open("e:\\myfile.txt", "w")
f.write("I am new!")
f.close()
#open and read the file after the appending:
f = open("e:\\myfile.txt", "r")
print(f.read())
f.close()
Output :-
Note : The "w"
technique overwrites the file in its entirety.
Create a New File
Use the open()
method to create a new Python file with one of the parameters below :
"x"
- Create - Create a file, returns an error when the file is present"a"
- Append - creates a file if there is no specific file"w"
- write - creates a file if the file is not specified
Example :- Create a file called "myfile2.txt" :
f = open("E:\\myfile2.txt", "x")
Result : a new empty file is created!
If you run the program second time, it will generate the follwing error:
Traceback (most recent call last):
f = open("e:\\myfile2.txt", "x")
FileExistsError: [Errno 17] File exists: 'e:\\myfile2.txt'
The a
and w
parameters are will not throw any exception.
Delete a File
You need to import the OS
module and use their os.remove()
function in order to delete a file:
Example :- Remove the file "e:\\myfile.txt" :
import os
os.remove("e:\\myfile.txt")
Check if File exist
You may wish to check whether the file exists before attempting to open or delete it to avoid error :
Example :- Check if file exists, then delete it :
import os
if os.path.exists("e:\\myfile.txt"):
os.remove("e:\\myfile.txt")
else:
print("The file does not exist")
Delete Folder
Use the os.rmdir()
method to remove a whole folder :
Example :- Remove the folder "myfolder" :
import os
os.rmdir("myfolder")
Note : only empty folders can be deleted.