Python File Handling (Reading and Writing)
File handling is an essential part of any application. Python has several functions for creating, reading, updating, and deleting files.
Opening a File
The key function for working with files in Python is the open() function. The open() function takes two parameters: filename, and mode.
There are four different methods (modes) for opening a file:
"r"- Read - Default value. Opens a file for reading, error if the file does not exist."a"- Append - Opens a file for appending, creates the file if it does not exist."w"- Write - Opens a file for writing, creates the file if it does not exist."x"- Create - Creates the specified file, returns an error if the file exists.
In addition, you can specify if the file should be handled as binary or text mode:
"t"- Text - Default value. Text mode."b"- Binary - Binary mode (e.g. images).
Reading Files
To open a file for reading, it is enough to specify the name of the file:
f = open("demofile.txt", "r")
print(f.read())
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how many characters you want to return:
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
You can return one line by using the readline() method:
f = open("demofile.txt", "r")
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Writing to an Existing File
To write to an existing file, you must add a parameter to the open() function:
"a"- Append - will append to the end of the file"w"- Write - will overwrite any existing content
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
The with Statement
It is good practice to use the with statement when working with files. This ensures that the file is closed properly, even if an exception is raised.
with open("demofile.txt", "r") as f:
content = f.read()
print(content)