目录
一、使用open函数读取文件二、按行读取文件三、写入文件四、使用readlines读取所有行五、使用writelines写入多行内容六、使用特定模块处理特定格式文件Python文件读写的6大实用方法涵盖了从基本读取到高级操作的不同场景。以下是这些方法的具体介绍:
一、使用open函数读取文件
这是Python中读取文件最基本的方式。使用open
函数以只读模式(‘r’)打开文件,并指定文件编码(如’utf-8’)。然后,可以使用文件对象的read
方法一次性读取整个文件内容。
with open('example.txt', 'r', encoding='utf-8') as file: content = file.read() print(content)
二、按行读取文件
对于大文件,一次性读取全部内容可能会消耗大量内存。因此,按行读取是一个更好的选择。使用for
循环逐行读取文件内容,并使用strip
方法去除每行末尾的换行符。
with open('example.txt', 'r', encoding='utf-8') as file: for line in file: print(line.strip())
三、写入文件
使用open
函数以写入模式(‘w’)或追加模式(‘a’)打开文件。然后,可以使用文件对象的write
方法将字符串写入文件。在’w’模式下,如果文件已存在,其内容会被清空;在’a’模式下,新内容会被追加到文件末尾。
# 写入文件with open('output.txt', 'w', encoding='utf-8') as file: file.write('Hello, Python!\n') file.write('Welcome to file operations.\n')# 追加内容到文件with open('output.txt', 'a', encoding='utf-8') as file: file.write('\nGoodbye, Python!')
四、使用readlines读取所有行
readlines
方法会读取文件中的所有行,并返回一个包含每行内容的列表。每个列表元素代表文件中的一行。
with open('example.txt', 'r', encoding='utf-8') as file: lines = file.readlines() for line in lines: print(line.strip())
五、使用writelines写入多行内容
writelines
方法接受一个字符串列表作为参数,并将每个字符串写入文件作为一行。这对于需要一次性写入多行内容的场景非常有用。
lines_to_write = ['First line.\n', 'Second line.\n', 'Third line.\n']with open('output.txt', 'w', encoding='utf-8') as file: file.writelines(lines_to_write)
六、使用特定模块处理特定格式文件
处理CSV文件:使用Python的csv
模块可以方便地读写CSV文件。通过创建csv.writer
对象来写入CSV文件,通过创建csv.reader
对象来读取CSV文件。import csv# 写入CSV文件with open('data.csv', 'w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['Name', 'Age', 'City']) writer.writerows([['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles']])# 读取CSV文件with open('data.csv', 'r', encoding='utf-8') as file: reader = csv.reader(file) for row in reader: print(row)处理JSON文件:使用Python的
json
模块可以方便地进行JSON数据的序列化和反序列化。通过json.dump
方法将Python对象序列化为JSON格式并写入文件,通过json.load
方法从文件中反序列化JSON数据。import json# 序列化对象并写入JSON文件data = {'name': 'Alice', 'age': 30, 'city': 'New York'}with open('data.json', 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4)# 从JSON文件中反序列化对象with open('data.json', 'r', encoding='utf-8') as file: loaded_data = json.load(file) print(loaded_data)