1 ''' 2 1. 使用with语句管理文件对象的打开和关闭,以确保及时释放资源。 3 2. 指定适当的打开模式来满足你的需求,例如只读、写入、追加等 4 3. 使用encoding参数指定正确的字符编码,以便正确处理文本文件 5 4. 对于大型文件,可以使用逐行读取或使用缓冲区来提高性能 6 5. 对于二进制文件,使用适当的打开模式,并在读取或写入时使用字节操作 7 6. 操作前,判断是否有操作权限 8 ''' 9 # 1. 使用with语句管理文件对象的打开和关闭,以确保及时释放资源 10 file_path = '033.txt' 11 12 # 打开文件并读取内容 13 with open(file_path, mode='r') as f: 14 content = f.read() 15 print(content) 16 17 # 2. 指定适当的打开模式来满足你的需求,例如只读、写入、追加等 18 19 # 以只读模式打开文件 20 with open(file_path, mode='r') as f: 21 content = f.read() 22 print(content) 23 24 # 以写入模式创建或覆盖文件 25 with open(file_path, mode='w') as f: 26 f.write('Hello, World!') 27 28 # 以追加模式打开文件 29 with open(file_path, mode='a') as f: 30 f.write('\nAppending additional content') 31 32 33 # 3. 使用encoding参数指定正确的字符编码,以便正确处理文本文件 34 # 以UTF-8编码打开文件 35 with open(file_path, mode='r', encoding='utf-8') as f: 36 content = f.read() 37 print(content) 38 39 # 4. 对于大型文件,可以使用逐行读取或使用缓冲区来提高性能。 40 41 # 逐行读取文件 42 with open(file_path, mode='r') as f: 43 for line in f: 44 print(line) 45 46 # 使用缓冲区读取文件 47 buffer_size = 4096 48 with open(file_path, mode='r', buffering=buffer_size) as f: 49 content = f.read() 50 print(content) 51 52 53 # 5. 对于二进制文件,使用适当的打开模式,并在读取或写入时使用字节操作。 54 55 # 以二进制模式读取文件 56 with open(file_path, mode='rb') as f: 57 data = f.read() 58 # 处理二进制数据 59 60 # 二进制数据 61 binary_data = b'\x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\x64\x21' 62 # 以二进制模式写入文件 63 with open(file_path, mode='wb') as f: 64 f.write(binary_data) 65 66 67 # 6. 访问权限 68 import os 69 70 file_path = "path/to/file.txt" 71 permission = os.W_OK # 检查写入权限 72 73 if os.access(file_path, permission): 74 print("有权限进行写入操作即open操作") 75 else: 76 print("没有权限进行写入操作")