import csv ''' csv文本操作,增删改查都需要遍历列表进行判断操作,如果要删除某行,可以del row[1] ,del用于删除列表元素。 def read_csv(file_path): """ 读取CSV文件内容 """ with open(file_path, 'r') as file: reader = csv.reader(file) for row in reader: print(row) def write_csv(file_path, data): """ 写入数据到CSV文件 """ with open(file_path, 'w', newline='') as file: writer = csv.writer(file) writer.writerows(data) def add_row(file_path, row_data): """ 添加一行数据到CSV文件 """ with open(file_path, 'a', newline='') as file: writer = csv.writer(file) writer.writerow(row_data) def update_row(file_path, row_index, new_row_data): """ 更新CSV文件中的一行数据 """ rows = [] with open(file_path, 'r') as file: reader = csv.reader(file) for row in reader: rows.append(row) if row_index < len(rows): rows[row_index] = new_row_data with open(file_path, 'w', newline='') as file: writer = csv.writer(file) writer.writerows(rows) def delete_row(file_path, row_index): """ 删除CSV文件中的一行数据 """ rows = [] with open(file_path, 'r') as file: reader = csv.reader(file) for row in reader: rows.append(row) if row_index < len(rows): del rows[row_index] with open(file_path, 'w', newline='') as file: writer = csv.writer(file) writer.writerows(rows) ''' # 往csv文件写入内容 def write_csv(): with open('./annex/data.csv', 'a', encoding='utf-8', newline='') as file: writer = csv.writer(file) writer.writerow(['1', '李四', '19']) writer.writerow(['2', '张三', '17']) writer.writerow(['3', '李贵', '26']) # 从csv文件中读取内容 def read_csv(): with open('./annex/data.csv', 'r', encoding='utf-8', newline='') as file: reader = csv.reader(file) for row in reader: print(row) def write_csvs(): with open('./annex/data.csv', 'w', encoding='utf-8', newline='') as file: writer = csv.writer(file) data=[['1','小明','语文','69'],[2,'小红','英语','86'],[3,'小东','数学','99']] writer.writerows(data) if __name__ == '__main__': write_csvs()
标签:14csv,文件,writer,file,reader,操作,path,csv,row From: https://www.cnblogs.com/chenzhi2023/p/17640934.html