
Python文件读写的6大实用方法涵盖了从基本读取到高级操作的不同场景。以下是这些方法的具体介绍:
这是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
方法会读取文件中的所有行,并返回一个包含每行内容的列表。每个列表元素代表文件中的一行。
with open('example.txt', 'r', encoding='utf-8') as file: lines = file.readlines() for line in lines: print(line.strip())
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
模块可以方便地读写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
模块可以方便地进行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)
以上这些方法涵盖了Python文件读写的常见场景,从基本的文件读取和写入到处理特定格式的文件,都提供了实用的解决方案。
到此这篇关于Python文件读写6大实用方法小结的文章就介绍到这了,更多相关Python文件读写方法内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!