Reading and Writing Files
Reading Files
Have you ever encountered a situation where you need to process a text file but don't know where to start? Don't worry, Python's file reading functionality can help you!
First, we use the open()
function to open a file and specify the read mode 'r'
:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
The above code will read the entire content of the file example.txt
into the content
variable and print it out. Note that we used the with
statement, which automatically closes the file after reading, avoiding resource leaks.
If the file is large, reading it all at once might consume a lot of memory. In this case, you can try reading it line by line:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # Remove the newline character at the end of the line
By looping, we can process the file content line by line, thus saving memory.
Writing Files
Since reading files is so simple, writing files must be a piece of cake, right? We open the file and specify the write mode 'w'
:
with open('example.txt', 'w') as file:
file.write('Hello, world!
')
file.write('Python programming is so fun!')
Running the above code will create an example.txt
file in the current directory and write two lines of text content. Note that the write()
method doesn't automatically add newline characters, you need to add manually.
If you want to append content to the end of the file, you can use the 'a'
mode:
with open('example.txt', 'a') as file:
file.write('
Hello again!')
This way you can add a new line of content to the original file.
Path Handling
In real projects, we often need to handle various file paths. Python's built-in os
module can help us easily accomplish these tasks.
File Renaming
For example, if you want to rename old_file.txt
to new_file.txt
in the current directory, you can do this:
import os
old_name = 'old_file.txt'
new_name = 'new_file.txt'
if os.path.exists(old_name):
os.rename(old_name, new_name)
else:
print("File does not exist!")
First, we check if the file exists using os.path.exists()
, and if it does, we call os.rename()
to rename it. Simple, right?
Advanced Techniques
Memory-Friendly
When dealing with large files, we need to be mindful of memory usage. The line-by-line reading method mentioned earlier is a memory-friendly approach.
Another common scenario is reading binary files, such as images, audio, etc. In this case, we need to open the file in binary mode 'rb'
:
with open('image.jpg', 'rb') as file:
binary_data = file.read()
The binary_data
read is the binary data of the image, which you can further process.
Automated Processing
Python excels at automating tasks, and file handling is no exception. You can use the os
and shutil
modules to batch process files.
For example, if we want to move all PDF files in the download folder to a new "PDF" folder:
import os
import shutil
downloads = '/path/to/downloads'
pdfs_dir = '/path/to/pdfs'
if not os.path.exists(pdfs_dir):
os.makedirs(pdfs_dir)
for filename in os.listdir(downloads):
if filename.endswith('.pdf'):
source = os.path.join(downloads, filename)
target = os.path.join(pdfs_dir, filename)
shutil.move(source, target)
This code first checks if the target folder exists, and creates one if it doesn't. Then it iterates through the download folder, moving all PDF files to the new folder.
You see, with a few lines of Python code, you can complete a repetitive and tedious task. Isn't that cool? I believe you can definitely use your imagination to write more automation scripts to improve work efficiency.
Summary
Through this article, you have learned the basic operations of Python file reading and writing, as well as some advanced uses. Remember, there are no absolute "best practices" in programming; the key is to choose the appropriate method based on the specific scenario.
File handling is just a small part of Python's functionality; it has many other powerful features waiting for you to explore. Keep your curiosity, be brave to try, and you will surely become an excellent Python programmer! If you have any questions, feel free to ask me anytime. The journey of programming is long, and I'm honored to accompany you along the way!