在Python中,可以使用os和pathlib库进行文件读写操作
首先,确保已经导入了所需的库:
import osfrom pathlib import Path接下来,创建一个文件路径对象:
file_path = Path("example.txt")1. 检查文件是否存在if file_path.exists(): print("文件存在")else: print("文件不存在")2. 读取文件内容if file_path.exists(): with open(file_path, "r", encoding="utf-8") as file: content = file.read() print("文件内容:") print(content)else: print("文件不存在")3. 写入文件内容with open(file_path, "w", encoding="utf-8") as file: file.write("Hello, World!")4. 在文件末尾追加内容with open(file_path, "a", encoding="utf-8") as file: file.write("\nThis is a new line.")5. 删除文件if file_path.exists(): os.remove(file_path) print("文件已删除")else: print("文件不存在")这些示例展示了如何使用pathlib库进行基本的文件读写操作。你可以根据自己的需求修改这些代码片段。


