File I/O in Python is straightforward. The built-in open function lets you specify a filename, the access mode, and encoding, then returns a file object that can be used for reading or writing. The access mode determines two things at once: whether you are dealing with text or binary data, and what kind of operation you want to perform on the file.
Here are the common file modes:
<table> <thead> <tr> <th>Mode</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>'r'</td>
<td>Read (default)</td>
</tr>
<tr>
<td>'w'</td>
<td>Write, truncating existing content first</td>
</tr>
<tr>
<td>'x'</td>
<td>Write, but raise an exception if the file already exists</td>
</tr>
<tr>
<td>'a'</td>
<td>Append content to the end of an existing file</td>
</tr>
<tr>
<td>'b'</td>
<td>Binary mode</td>
</tr>
<tr>
<td>'t'</td>
<td>Text mode (default)</td>
</tr>
<tr>
<td>'+'</td>
<td>Update mode, allowing both reading and writing</td>
</tr>
</tbody>
</table>
When handling files in Python, exception handling is important. A safe pattern is to wrap file operations in try / except so that unexpected runtime problems do not crash the program without explanation.
A standard example looks like this:
def main():
f = None
try:
f = open('文件.txt', 'r', encoding='utf-8')
print(f.read())
except FileNotFoundError:
print('无法打开指定的文件!')
except LookupError:
print('指定了未知的编码!')
except UnicodeDecodeError:
print('读取文件时解码错误!')
finally:
if f:
f.close()
if __name__ == '__main__':
main()
Any code that may fail at runtime can be placed inside a try block. One or more except blocks can then be used to catch specific exceptions.
In the example above:
FileNotFoundErroris raised if the target file does not exist.LookupErroris raised if an unknown encoding name is specified.UnicodeDecodeErroris raised if the file cannot be decoded using the chosen encoding while being read.
The finally block is used to close the file and release external resources. This block runs whether execution succeeds or fails, so it is a reliable place for cleanup. Even if the program exits by calling the exit function from the sys module, the finally block still executes, because exit effectively raises a SystemExit exception. That is why finally is often treated as the “always runs” block, and it is especially suitable for resource release.
If you do not want to close the file manually in finally, Python provides a cleaner option: the context manager syntax with with. Once execution leaves the with block, the file resource is released automatically.
Reading a file is not limited to calling read(). You can also iterate through the file line by line with a for-in loop, or use readlines() to load all lines into a list.
import time
def main():
# 一次性读取整个文件内容
with open('文件.txt', 'r', encoding='utf-8') as f:
print(f.read())
# 通过for-in循环逐行读取
with open('文件.txt', mode='r') as f:
for line in f:
print(line, end='')
time.sleep(0.5)
print()
# 读取文件按行读取到列表中
with open('文件.txt') as f:
lines = f.readlines()
print(lines)
if __name__ == '__main__':
main()
These three approaches are useful in different situations:
read()loads the entire file content at once.- Iterating with
for line in fis suitable when you want to process a file one line at a time. readlines()returns a list in which each item is one line from the file.
Once text and binary data can be written to files, a natural next question is how to store structured data such as lists or dictionaries. A common solution is JSON.
JSON stands for JavaScript Object Notation. It originally came from JavaScript object literal syntax, but it is now widely used for data exchange across systems and programming languages. The reason is simple: JSON is plain text, and plain text can be handled almost everywhere. In practice, JSON has largely replaced XML as the de facto standard for data exchange between heterogeneous systems.
JSON maps cleanly to Python data types:
<table> <thead> <tr> <th>JSON</th> <th>Python</th> </tr> </thead> <tbody> <tr> <td>object</td> <td>dict</td> </tr> <tr> <td>array</td> <td>list</td> </tr> <tr> <td>string</td> <td>str</td> </tr> <tr> <td>number (int / real)</td> <td>int / float</td> </tr> <tr> <td>true / false</td> <td>True / False</td> </tr> <tr> <td>null</td> <td>None</td> </tr> </tbody> </table>Saving a Python dictionary to a JSON file can be done with the json module:
import json
def main():
mydict = {
'name': '小风',
'age': 20,
'qq': 95849158,
'friends': ['张三', '李四'],
'cars': [
{'brand': 'BYD', 'max_speed': 180},
{'brand': 'Audi', 'max_speed': 280},
{'brand': 'Benz', 'max_speed': 320}
]
}
try:
with open('data.json', 'w', encoding='utf-8') as fs:
json.dump(mydict, fs)
except IOError as e:
print(e)
print('保存数据完成!')
if __name__ == '__main__':
main()
The json module provides four especially important functions:
dump— serialize a Python object to a file in JSON formatdumps— convert a Python object into a JSON-formatted stringload— deserialize JSON data from a file into a Python objectloads— deserialize JSON content from a string into a Python object