【python】【pycharm】+读写csv文件/其他格式配置文件
https://blog.csdn.net/qq_39413365/article/details/88760885
step1:数据写入csv配置文件
1 def csv_writer(): 2 '''写入csv文件''' 3 headers = ["编号", "课程", "讲师"] 4 5 rows = [ 6 (1, "A", "AA"), 7 (2, "B", "BB"), 8 (3, "C", "CC") 9 ] 10 with open("ZGXTest.csv", "w", encoding="GBK", newline="") as f: 11 writer = csv.writer(f) 12 writer.writerow(headers) 13 writer.writerows(rows)
step2:读取csv文件数据
1 def csv_reader(): 2 '''读取csv文件''' 3 with open("ZGXTest.csv", encoding="GBK") as f: 4 # reader = csv.DictReader(f) 5 # 读取每一行 6 reader = csv.reader(f) 7 # 配置表头 8 headers = next(reader) 9 # 打印表头 10 print(headers) 11 # 打印每一行(无表头) 12 for row in reader: 13 print(row)
step3:调用
1 if __name__ == "__main__": 2 csv_writer() 3 csv_reader()
完整代码
1 import csv 2 3 4 def csv_writer(): 5 '''写入csv文件''' 6 headers = ["编号", "课程", "讲师"] 7 8 rows = [ 9 (1, "A", "AA"), 10 (2, "B", "BB"), 11 (3, "C", "CC") 12 ] 13 with open("ZGXTest.csv", "w", encoding="GBK", newline="") as f: 14 writer = csv.writer(f) 15 writer.writerow(headers) 16 writer.writerows(rows) 17 18 19 def csv_reader(): 20 '''读取csv文件''' 21 with open("ZGXTest.csv", encoding="GBK") as f: 22 # reader = csv.DictReader(f) 23 # 读取每一行 24 reader = csv.reader(f) 25 # 配置表头 26 headers = next(reader) 27 # 打印表头 28 print(headers) 29 # 打印每一行(无表头) 30 for row in reader: 31 print(row) 32 33 34 if __name__ == "__main__": 35 csv_writer() 36 csv_reader()
效果
打印结果
文件内容
如果忍耐算是坚强 我选择抵抗 如果妥协算是努力 我选择争取