本文将从多个方面对Python常用文件处理进行详细的阐述。
一、文件读取与写入
文件读取与写入是Python中常用的文件处理操作。
1、文件读取:
file = open("example.txt", "r") content = file.read() file.close() print(content)
通过open()函数打开文件,第一个参数是文件路径,第二个参数是打开模式("r"表示只读)。使用read()方法可以读取文件内容,然后使用close()方法关闭文件。
2、文件写入:
file = open("example.txt", "w") file.write("Hello, World!") file.close()
使用open()函数打开文件时,第二个参数为"w"表示写入模式。通过write()方法可以写入内容,然后使用close()方法关闭文件。
二、CSV文件处理
CSV文件是常用的数据交换格式,在Python中可以使用csv模块进行处理。
1、读取CSV文件:
import csv with open("example.csv", "r") as file: csv_reader = csv.reader(file) for row in csv_reader: print(row)
使用csv模块的reader()函数读取CSV文件,通过循环遍历可以逐行读取内容。
2、写入CSV文件:
import csv data = [ ["Name", "Age", "Gender"], ["John", "25", "Male"], ["Emma", "30", "Female"] ] with open("example.csv", "w", newline="") as file: csv_writer = csv.writer(file) csv_writer.writerows(data)
使用csv模块的writer()函数写入CSV文件,通过writerows()方法可以写入多行数据。
三、JSON文件处理
JSON文件是常用的数据存储格式,在Python中可以使用json模块进行处理。
1、读取JSON文件:
import json with open("example.json", "r") as file: data = json.load(file) print(data)
使用json模块的load()函数读取JSON文件,可以将JSON文件中的数据转换为Python对象。
2、写入JSON文件:
import json data = { "name": "John", "age": 25, "gender": "Male" } with open("example.json", "w") as file: json.dump(data, file)
使用json模块的dump()函数写入JSON文件,可以将Python对象转换为JSON格式后写入文件。