当前位置:首页>python>Python读写CSV文件

Python读写CSV文件

  • 2026-08-26 08:06:25
Python读写CSV文件
Python 读取CSV文件;
使用csv.reader()和csv.writer().
import csv
import os
dir_path = r'C:\Users\86182\Desktop\内置CSV模块'
file_name = "mat_info.csv"
file_path = os.path.join(dir_path,file_name)
with open (file_path,'+r') as file:
    lines = csv.reader(file,quotechar="'")
#    data = list(lines)
#    print(data)
for line in lines:
# line 是一个列表
print(type(line))
print(line)
# 输入需要写入的数据
new_data = [
    ['DC04',0.6,170]
]
# 打开文件并写入(注意:写入时需指定 newline='' 避免空行,encoding='utf-8' 防中文乱码)
# 打开模式改为 'a'(追加)
with open(file_path, 'a', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerows(new_data)
使用csv.DictReader()和csv.DictWriter().
import csv
import os
dir_path = r'C:\Users\86182\Desktop\内置CSV模块'
file_name = "mat_info.csv"
file_path = os.path.join(dir_path,file_name)
with open (file_path,'+r') as file:
    lines = csv.DictReader(file,quotechar="'")
#    data = list(lines)
#    print(data)
#   获取表头
    header = lines.fieldnames
    column0 = header[0]
    column1 = header[1]
    column2 = header[2]
print("CSV 表头(字典的键):", lines.fieldnames)
for line in lines:
#        print(type(line))
print(f"'material':{line[column0]},'A':{line[column1]},'Yield':{line[column2]}")
# 输入需要写入的数据 
new_data = [
    {'material':'DC06','A':0.7,'Yield':170}
]
# 表头必须和已有CSV的表头一致!(追加方式写入),新建的话需要先写入表头。
fieldnames = ['material', 'A', 'Yield']
with open(file_path, 'a', newline='', encoding='utf-8') as file:
    writer = csv.DictWriter(file,fieldnames=fieldnames)
    writer.writerows(new_data)

最新文章

随机文章