我有以下格式的CSV文件:
Name Seq
a atcg
b ggct
c ccga
我希望为每一行创建一个单独的文本文件,其中命名的文件基于一列命名,文件的内容基于另一列。
我目前有以下代码:
import csv
with open('prac.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
file_name ='{0}.txt'.format(row['name'])
with open(file_name, 'w') as f:
pass
将使用“名称”列中的每一行的值创建文本文件。但是我不确定如何将'Seq'列写入每个文本文件。
答案 0 :(得分:1)
您非常亲密:
import csv
with open('prac.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row) #you can remove this, see below
file_name ='{0}.txt'.format(row['Name'])
with open(file_name, 'w') as f:
f.write(row['Seq'])
我添加了print
语句只是为了显示每个“ row
”的含义;您已经在创建Name
时键入了file_name
,而在编写时只需键入Seq
:
OrderedDict([('Name', 'a'), ('Seq', 'atcg')])
OrderedDict([('Name', 'b'), ('Seq', 'ggct')])
OrderedDict([('Name', 'c'), ('Seq', 'ccga')])