try-except语句

# Handle exceptions with a try/except block
try:
    # Use "raise" to raise an error
    raise IndexError("This is an index error")
except IndexError as e:
    pass                 # Refrain from this, provide a recovery (next example).
except (TypeError, NameError):
    pass                 # Multiple exceptions can be processed jointly.
else:                    # Optional clause to the try/except block. Must follow
                         # all except blocks.
    print("All good!")   # Runs only if the code in try raises no exceptions
finally:                 # Execute under all circumstances
    print("We can clean up resources here")

文件操作

  • python和shell文件操作的基本思想:文件是迭代器,逐行。每行是字符串。

with语句用于文件读写

  • with语句可以自动关闭文件,避免忘记关闭文件造成资源泄露。
# Instead of try/finally to cleanup resources you can use a with statement
with open("myfile.txt") as f:
    for line in f:
        print(line)

文件写入

  • 两种格式:字符串格式和json格式
    • 字符串格式:简单直接,但读取时需要手动解析字符串。
    • json格式:易于读取和解析,适合与其他程序或语言交互。
# Writing to a file
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w") as file:
    file.write(str(contents))        # writes a string to a file

import json
with open("myfile2.txt", "w") as file:
    file.write(json.dumps(contents))  # writes an object to a file

文件读取

# Reading from a file
with open("myfile1.txt") as file:
    contents = file.read()           # reads a string from a file
print(contents)
# print: {"aa": 12, "bb": 21}

with open("myfile2.txt", "r") as file:
    contents = json.load(file)       # reads a json object from a file
print(contents)
# print: {"aa": 12, "bb": 21}

pathlib中的 Path 类读写

from pathlib import Path

path = Path('data.txt')
contents = path.read_text() # 类型为 <class 'str'>
lines = contents.splitlines() # 类型为 <class 'list'>

path.write_text("I love programing.") # 只能写入str
path.write_text("I hate programing.") # 此时文件内的内容只有"I hate programing."

文件写入的注意事项

  • 若文件已存在,​​清空其所有内容​​,再写入新数据;若文件不存在,​​创建新文件​​后写入。
  • 每次path.write_text()或者open("myfile2.txt", "w") as file都会覆盖文件之前的内容
  • path.write_text()只支持一次写入,不支持多次写入
  • open("myfile2.txt", "a"):使用追加模式可以避免已存在文件被覆盖