我正在研究一些代码,以从输入的.txt文件生成两个新的CSV文件。 .txt文件具有40列数据,我正在编写两个新的csv文件,每个文件仅从.txt文件中占据2列。
我的代码运行良好,几乎可以满足我的需求。最后一步是在两个新的csv输出中重命名原始标头。
这是我的代码:
import csv
QATargetHeaders = ['FNAME','LNAME']
FinalTargetHeaders = ['PROJECT_CODE','PHONE_NUMBER']
with open('TEST.txt','r') as csv_input, open('Test_QA2.csv','w') as csv_output:
reader = csv.DictReader(csv_input, delimiter='^')
writer = csv.DictWriter(csv_output, fieldnames=QATargetHeaders, extrasaction='ignore')
writer.writeheader()
for line in reader:
writer.writerow(line)
with open('TEST.txt','r') as csv_input, open('Test_FINAL.csv','w') as csv_output:
reader = csv.DictReader(csv_input, delimiter='^')
writer = csv.DictWriter(csv_output, fieldnames=FinalTargetHeaders, extrasaction='ignore')
writer.writeheader()
for line in reader:
writer.writerow(line)
对于TEST_QA2.csv,我需要更改标题:
FNAME = First Name
LNAME = Last Name
对于TEST_FINAL.csv,我需要更改标题:
PROJECT_CODE = PROJECT ID
PHONE_NUMBER = DEVICE1
有人可以帮我弄清楚如何在这里重写标题吗?必须将TargetHeaders定义为.txt文件中的确切列名,以便我的作者知道要复制的内容。在此先谢谢您
答案 0 :(得分:0)
line
是dict
。字典键用作标题。因此,在编写新的csv之前,您必须重命名密钥。您可以通过dict理解来做到这一点。
import csv
QATargetHeaders = ['First Name','Last Name']
FinalTargetHeaders = ['PROJECT ID','DEVICE1']
map_QATargetHeaders = (('FNAME', 'First Name'), ('LNAME', 'Last Name'))
map_FinalTargetHeaders = (('PROJECT_CODE', 'PROJECT ID'), ('PHONE_NUMBER', 'DEVICE1LNAME'))
with open('TEST.txt','r') as csv_input, open('Test_QA2.csv','w') as csv_output:
reader = csv.DictReader(csv_input, delimiter='^')
writer = csv.DictWriter(csv_output, fieldnames=QATargetHeaders, extrasaction='ignore')
writer.writeheader()
for line in reader:
line = {map[1]:line[map[0]] for map in map_QATargetHeaders}
writer.writerow(line)
with open('TEST.txt','r') as csv_input, open('Test_FINAL.csv','w') as csv_output:
reader = csv.DictReader(csv_input, delimiter='^')
writer = csv.DictWriter(csv_output, fieldnames=FinalTargetHeaders, extrasaction='ignore')
writer.writeheader()
for line in reader:
line = {map[1]:line[map[0]] for map in map_FinalTargetHeaders}
writer.writerow(line)
答案 1 :(得分:0)
将writeheader
与字典配合使用,而不是writerow
,将旧标头映射到新标头。然后,您可以像以前一样写其他行。
QATargetHeaders = {'FNAME': 'First Name','LNAME': 'Last Name'}
FinalTargetHeaders = {'PROJECT_CODE': 'PROJECT ID','PHONE_NUMBER': 'DEVICE1'}
...
writer = csv.DictWriter(csv_output, fieldnames=QATargetHeaders, extrasaction='ignore')
writer.writerow(QATargetHeaders) # instead of writeheader
for line in reader:
writer.writerow(line)
...
(从Python 3.7 dictionaries preserve order开始,因此这些列将以正确的顺序显示。如果使用的是Python的早期版本,则需要创建一个单独的字段名称列表,或者使用{{3} },以确保列以正确的顺序出现在CSV文件中。)