In Python programming, file read and write operations are one of the important means to achieve data persistence. Whether it is saving intermediate results during program execution, logging information, or storing user input data, these operations are very practical. Today, let’s delve into the topic of data persistence through file read and write operations in Python!
File Writing
First, let’s look at how to write data to a file. Python provides simple yet powerful methods for writing files, allowing you to easily save various types of data to disk!
Taking writing to a text file as an example, if we want to create a file named example.txt and write some text content into it, we can do it like this:
file = open('example.txt', 'w')
file.write('This is the first line of text\
')
file.write('This is the second line of text\
')
file.close()
Here, we use the open
function to open a file and specify the mode as 'w'
, which indicates write mode. If the file does not exist, it will be created; if it exists, the original content will be overwritten! Then, we use the write
function to write text to the file, adding a newline character \
at the end of each line to ensure that each line occupies a separate line. Finally, don’t forget to call the close
function to close the file and release system resources!
In addition to writing simple text, if the data to be written is of other types, such as lists or dictionaries, you can convert them to string format before writing, like this:
my_list = ['apple', 'banana', 'orange']
file = open('fruits.txt', 'w')
file.write(str(my_list))
file.close()
However, writing data this way may not be convenient for subsequent processing when reading. If you want to store each element on a separate line, you can write them one by one in a loop, like this:
my_list = ['apple', 'banana', 'orange']
file = open('fruits.txt', 'w')
for fruit in my_list:
file.write(fruit + '\
')
file.close()
File Reading
Having discussed writing, let’s now look at how to read data from a file! Reading files is also very easy to get started with!
Using the previously created example.txt as an example, if we want to read all the contents, we can write it like this:
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
Here, we open the file in read-only mode 'r'
using the open
function, then use the read
function to read the entire file content and assign it to the variable content
. Finally, we print it out to see! Note that if the file is large, reading all content at once may consume a lot of memory. In this case, you can consider reading line by line, for example:
file = open('example.txt', 'r')
for line in file:
print(line.strip()) # Use the strip method to remove trailing newline characters and other whitespace before printing!
file.close()
This line-by-line reading method is suitable for handling large text files, as it does not cause memory pressure and allows for real-time processing of each line of data, making it very convenient! If you want to restore the read data to its original data type, for example, reading back a list of elements stored line by line from a file, you can do it like this:
my_list = []
file = open('fruits.txt', 'r')
for line in file:
my_list.append(line.strip()) # Add each line after removing whitespace to the list!
print(my_list) # Print the list after using the strip method to remove trailing newline characters and other whitespace!
file.close()
File Read and Write Modes and Considerations
When using Python for file read and write operations, in addition to the basic modes mentioned above, there are some other useful modes and considerations to keep in mind! For example, if you want to add new content to an existing file without overwriting the original content, you can open the file in append mode, like this:
file = open('example.txt', 'a')
file.write('This is an appended line of text\
')
file.close()
Here, the mode is specified as 'a'
, which indicates append mode. When you run this code again, it will add new text at the end of the example.txt file! There is also binary mode, which is used when dealing with non-text data, such as images, audio, video, and other binary files. For example, to read an image and save it, you can do it like this:
with open('image.jpg', 'rb') as f: # Open the image in binary read mode!
data = f.read()
with open('new_image.jpg', 'wb') as f: # Create a new image in binary write mode!
f.write(data)
Here, the first open
function opens the image in binary read mode, and the second open
function creates a new image in binary write mode and writes the read data into it. A special reminder is that after operating on a file, you must close it in a timely manner; otherwise, it may lead to data loss or resource occupation issues. However, there is a more elegant way to manage file operations, which is to use the with
statement. It automatically closes the file after the code block ends, for example, the above code can also be written like this:
with open('image.jpg', 'rb') as f: # Open the image in binary read mode!
data = f.read()
with open('new_image.jpg', 'wb') as f: # Create a new image in binary write mode!
f.write(data)
# Both files will be automatically closed after the with statement block ends, no need to manually call the close method!
This makes the code cleaner and avoids the potential risk of forgetting to close the file. By mastering these Python file read and write techniques, we can easily achieve data persistence, whether for simple text or complex binary data, we can handle it properly! I hope everyone can skillfully apply these techniques in actual programming to make their code more complete and efficient! Have you encountered any interesting data persistence scenarios? Feel free to share with me; it might inspire others!