Each and every developer must have dealt with files in their career. In Python, handling file is simpler and more powerful compare to other languages.
In this blog post, we’ll see how to handle file operations with clear explaination and examples.
Below are the basic file operations in Python:
- Create
- Read
- Write
- Append
for each operation above, we need a file to be opened (Note: For the write operation, it will create a new file if it does not exist.). The syntax to open the file is:
file = open("FileName", "Operation") Read
lets first see how the code to read the file in Python looks like:
f = open("Test.txt", "r")
data = f.read()
print(data)
f.close()Lets understand the code line by line.
Line: 1
f = open("Test.txt", "r")open() is built in Python function which accepts two parameters:
- File Path: The path of the file
- Mode: Mode in which file opens. (
r: read,w: write,a: append,x: create)
and this function returns the file object which is assigned to the variable ‘f’.
Note: Since this blog is for beginners, only common file modes (r, w, a and x) are discussed. Other modes such as r+, w+, a+, rb, wb exstis but are not required at this stage
Line: 2
data = f.read()f.read(): will read all content of the data.
It also accepts an optional parameter ‘size’. if the size is mentioned as parameter, it will read the characters mentioned in the size. for example f.read(10) will read first 10 characters and will stop reading further.
Python also provides other methods to read file content as below:
readLine([size]) : Will read one line at a time and stops reading when it reaches new line character ‘\n’. If the size parameter mentioned then it will stop reading after number of characters mentioned in the size. Code example:
f = open("Test.txt", "r")
first_line = f.readline() # reads first line
second_line = f.readline() # reads second line
third_line = f.readline(5) # reads 5 caracters of third line
third_line_2 = f.readline() # reads remaining characters from third line
f.close()readLines([Size]): Will read all lines and returns the array. Each array element in the result represents each line of the file content. If size is provided, it will read number of characters mentioned.
Line 3
print(data)Will print file content in console output.
Line 4
f.close()it will close the file and release the system resource associated to it. Always, make sure to close the file after using it.
Write
To write the file, you need to use the ‘w’ as a mode parameter. This:
- Creates new file if it does not exist.
- Overwrites file If file already exists.
file = open("test.txt", "w")
file.write("Hello Developer")
file.close()Append
Append mode ‘a’ will append a content to the end of a file. New file will be created if file does not exist.
file = open("text.txt", "a")
file.write("\nThis line new line.")
file.close()Best Practice (‘with' statement)
In all above example, after performing all operations, we close the file explicitly using f.close(). But if you forget to close the file, it will lead to resource leaks and performance issues. To avoide that Python provides a safety way using with statement:
with open("example.txt", "r") as file:
content = file.read()
print(content)Using with statement, you dont need to close the file explicitly. It will automatically close the file.