引言文本文件.txt是最基础、最通用的数据存储格式之一广泛应用于日志记录、配置文件、数据交换等场景。Python提供了简单易用的内置方法来读写txt文件无需额外安装库。本文将详细介绍Python中读写txt文件的各种方法包括基础操作和高级技巧。1. 写入txt文件1.1 使用open()和write()方法这是最基本的写入方法# 打开文件进行写入如果文件不存在会自动创建withopen(example.txt,w,encodingutf-8)asfile:file.write(这是第一行文本\n)file.write(这是第二行文本\n)file.write(这是第三行文本\n)参数说明w写入模式会覆盖已存在的文件encodingutf-8指定编码推荐始终使用UTF-8with语句确保文件正确关闭即使发生异常1.2 写入多行内容使用writelines()方法可以一次性写入多行lines[第一行\n,第二行\n,第三行\n]withopen(multiline.txt,w,encodingutf-8)asfile:file.writelines(lines)1.3 追加内容到文件使用a模式可以在文件末尾追加内容而不覆盖原有内容withopen(example.txt,a,encodingutf-8)asfile:file.write(这是追加的内容\n)1.4 格式化写入结合f-string或format()方法可以写入动态内容name张三age25withopen(formatted.txt,w,encodingutf-8)asfile:file.write(f姓名:{name}, 年龄:{age}\n)# 或者使用formatfile.write(职业: {}\n.format(工程师))2. 读取txt文件2.1 读取整个文件withopen(example.txt,r,encodingutf-8)asfile:contentfile.read()print(content)2.2 逐行读取withopen(example.txt,r,encodingutf-8)asfile:forlineinfile:# 迭代器方式逐行读取print(line.strip())# strip()去除行尾换行符2.3 读取所有行到列表withopen(example.txt,r,encodingutf-8)asfile:linesfile.readlines()# 返回包含所有行的列表fori,lineinenumerate(lines,1):print(f第{i}行:{line.strip()})2.4 处理大文件对于大文件建议使用逐行读取或分块读取以避免内存问题# 方法1逐行读取内存友好withopen(large_file.txt,r,encodingutf-8)asfile:forlineinfile:process_line(line)# 处理每一行的函数# 方法2分块读取chunk_size1024*1024# 1MBwithopen(large_file.txt,r,encodingutf-8)asfile:whileTrue:chunkfile.read(chunk_size)ifnotchunk:breakprocess_chunk(chunk)# 处理每个块的函数3. 文件路径处理3.1 相对路径与绝对路径# 相对路径相对于当前工作目录withopen(./data/example.txt,r)asfile:...# 绝对路径推荐使用os.path或pathlib处理跨平台路径importos file_pathos.path.join(C:,Users,username,Documents,example.txt)withopen(file_path,r)asfile:...3.2 使用pathlibPython 3.4推荐frompathlibimportPath# 创建Path对象file_pathPath(data/example.txt)# 检查文件是否存在iffile_path.exists():# 读取文件contentfile_path.read_text(encodingutf-8)print(content)# 写入文件file_path.write_text(新内容\n,encodingutf-8)4. 编码问题处理4.1 常见编码问题UnicodeDecodeError通常是因为文件编码与指定编码不匹配UnicodeEncodeError写入时使用了不支持的字符4.2 解决方案# 尝试常见编码encodings[utf-8,gbk,gb2312,big5,latin1]defread_with_fallback(filename):forencodinginencodings:try:withopen(filename,r,encodingencoding)asfile:returnfile.read()exceptUnicodeDecodeError:continueraiseUnicodeDecodeError(f无法解码文件{filename}尝试了所有常见编码)# 写入时忽略无法编码的字符不推荐除非必要withopen(output.txt,w,encodingutf-8,errorsignore)asfile:file.write(包含特殊字符的文本)5. 高级技巧5.1 同时读写文件使用r模式可以同时读写文件withopen(example.txt,r,encodingutf-8)asfile:contentfile.read()file.seek(0)# 移动指针到文件开头file.write(新内容\ncontent)# 在开头插入内容5.2 CSV格式文本处理虽然CSV是专门格式但常以.txt扩展名保存importcsv# 写入CSV格式文本withopen(data.txt,w,newline,encodingutf-8)asfile:writercsv.writer(file)writer.writerow([姓名,年龄,城市])writer.writerow([张三,25,北京])writer.writerow([李四,30,上海])# 读取CSV格式文本withopen(data.txt,r,encodingutf-8)asfile:readercsv.reader(file)forrowinreader:print(row)5.3 JSON格式文本处理对于结构化数据JSON是更好的选择但仍可能保存为.txtimportjson data{name:张三,age:25,skills:[Python,数据分析]}# 写入JSONwithopen(data.txt,w,encodingutf-8)asfile:json.dump(data,file,ensure_asciiFalse,indent4)# 读取JSONwithopen(data.txt,r,encodingutf-8)asfile:loaded_datajson.load(file)print(loaded_data)6. 最佳实践始终使用with语句确保文件正确关闭明确指定编码推荐始终使用UTF-8处理异常特别是文件不存在或权限问题时避免硬编码路径使用os.path或pathlib大文件处理使用逐行或分块读取路径分隔符跨平台时使用os.path.join()或pathlib完整示例frompathlibimportPathdefprocess_file_operations():# 创建目录如果不存在data_dirPath(data)data_dir.mkdir(exist_okTrue)# 写入文件file_pathdata_dir/example.txtfile_path.write_text(第一行文本\n第二行文本\n第三行文本\n,encodingutf-8)# 读取并处理文件iffile_path.exists():contentfile_path.read_text(encodingutf-8)print(文件内容:)print(content)# 追加内容file_path.write_text(content\n这是追加的内容\n,encodingutf-8)else:print(文件不存在)if__name____main__:process_file_operations()结论Python提供了简单而强大的工具来处理txt文件的读写操作。从基本的文件操作到高级的路径处理和编码管理掌握这些技术可以让你高效地处理各种文本数据场景。对于简单的任务内置的open()函数通常就足够了对于更复杂的路径操作或跨平台需求pathlib模块提供了更现代的解决方案。记住始终考虑文件编码和异常处理这将使你的代码更加健壮和可靠。