Python文件处理与模块使用全解析
1. Python文件处理模式
1.1 ‘a’ 模式
在Python中, 'a' 模式即追加模式。若文件存在,文件指针会位于文件末尾;若文件不存在,则会创建一个新文件用于写入。以下是相关操作示例:
1. 删除并重新创建文件
python import os os.remove('C://Python312//ch02//file2.txt') os.path.isfile('C://Python312//ch02//file2.txt') # 输出 False
2. 以追加模式打开文件并写入内容
python with open('C://Python312//ch02//file2.txt', 'a') as f: f.write('This is line 1.')
3. 尝试在追加模式下读取文件(会报错)
python with open('C://Python312//ch02//file2.txt', 'a') as f: f_read = f.read() print(f_read) # 报错:io.UnsupportedOperation: not readable
4. 以读取模式打开文件并打印内容
python with open('C://Python312//ch02//fil
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



