在Python编程中,文件读取与保存是基础且重要的操作。掌握不同格式文件的存储技巧,能够帮助我们更高效地处理数据。本文将详细介绍Python中常用的文件读取与保存方法,包括文本文件、CSV文件、JSO...
在Python编程中,文件读取与保存是基础且重要的操作。掌握不同格式文件的存储技巧,能够帮助我们更高效地处理数据。本文将详细介绍Python中常用的文件读取与保存方法,包括文本文件、CSV文件、JSON文件等,并提供相应的代码示例。
文本文件是最常见的文件格式之一,Python提供了内置的读写方法。
with open('example.txt', 'w') as file: file.write("Hello, World!")with open('example.txt', 'r') as file: content = file.read() print(content)CSV(Comma-Separated Values)文件是一种以逗号分隔的纯文本文件,常用于数据交换。
import csv
with open('example.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Name', 'Age', 'City']) writer.writerow(['Alice', 30, 'New York']) writer.writerow(['Bob', 25, 'Los Angeles'])import csv
with open('example.csv', 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row)JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。
import json
data = { 'Name': 'Alice', 'Age': 30, 'City': 'New York'
}
with open('example.json', 'w') as jsonfile: json.dump(data, jsonfile)import json
with open('example.json', 'r') as jsonfile: data = json.load(jsonfile) print(data)通过本文的介绍,相信你已经掌握了Python中不同格式文件的读取与保存技巧。在实际应用中,根据需求选择合适的文件格式和存储方法,能够提高我们的工作效率。