Python轻松管理你的CSV文件:读取、写入、删除一步到位!
引言:
代码实现了功能:读取 CSV 文件、获取指定单元格的值、写入 CSV 文件、追加数据到 CSV 文件、删除 CSV 文件
代码封装如下:
import csv
import os
class CSVHandler:
def __init__(self, file_path):
"""
初始化CSVHandler对象
:param file_path: csv文件的路径
"""
self.file_path = file_path #todo 存储文件路径
def read_csv(self):
data = [] #todo 用于存储csv文件的所有行数据
try:
with open(self.file_path, 'r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
#todo 逐行读取csv内容,并将每一行数据添加到data列表中
for row in reader:
data.append(row)
#todo 打印读取的所有数据(可选)
for row in data:
print(row)
return data #todo 返回读取到的所有数据
except FileNotFoundError:
print(f"文件 '{self.file_path}' 未找到")
except Exception as e:
print(f"读取文件时发生错误: {e}")
def get_csv_cell_value(self, row_number, col_letter):
try:
with open(self.file_path, 'r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
data = list(reader) #todo 将csv文件内容读取为列表
row_index = row_number - 1 #todo 将行号转换为列表的索引(Python索引从0开始)
col_index = ord(col_letter.lower()) - 97 #todo 将列字母转换为对应的索引,'A' -> 0, 'B' -> 1, 等等
if row_index < 0 or row_index>= len(data):
print(f"行号 {row_number} 超出了有效范围")
return None
if col_index < 0 or col_index>= len(data[row_index]):
print(f"列字母 {col_letter} 超出了有效范围")
return None
return data[row_index][col_index] #todo 返回指定单元格的值
except FileNotFoundError:
print(f"文件 '{self.file_path}' 未找到")
except Exception as e:
print(f"获取单元格值时发生错误: {e}")
def write_csv(self, data):
try:
with open(self.file_path, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
#todo 将传入的数据逐行写入csv文件
for row in data:
writer.writerow(row)
print("数据已成功写入文件")
except Exception as e:
print(f"写入文件时发生错误: {e}")
def append_csv(self, data):
try:
with open(self.file_path, 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
#todo 将传入的数据逐行追加到csv文件
for row in data:
writer.writerow(row)
print("数据已成功追加到文件")
except Exception as e:
print(f"追加数据时发生错误: {e}")
def delete_csv(self):
try:
if os.path.exists(self.file_path):
os.remove(self.file_path) #todo 删除文件
print(f"文件 '{self.file_path}' 已删除")
else:
print(f"文件 '{self.file_path}' 不存在")
except Exception as e:
print(f"删除文件时发生错误: {e}")
if __name__ == '__main__':
#todo 示例代码:以下代码将执行CSV操作
file_path = r"D:\1.csv" #todo 设置文件路径
csv_handler = CSVHandler(file_path) #todo 创建CSVHandler对象
#todo 读取csv文件
csv_handler.read_csv()
#todo 获取指定单元格的值(例如第二行,第三列,列标为'C')
cell_value = csv_handler.get_csv_cell_value(row_number=2, col_letter='C')
if cell_value is not None:
print(f"指定单元格的值是: {cell_value}")
#todo 写入数据(覆盖现有文件内容)
data_to_write = [["Name", "Age", "City"], ["Alice", 30, "New York"], ["Bob", 25, "Los Angeles"]]
csv_handler.write_csv(data_to_write)
#todo 追加数据到文件末尾
data_to_append = [["张三", 35, "上海"], ["李四", 40, "深圳"]]
csv_handler.append_csv(data_to_append)
#todo 删除csv文件
#todo csv_handler.delete_csv()
注意:函数csv_handler.delete_csv()此操作将永久删除文件,使用时请小心