I have a CSV file in the following format:
Name Seq
a atcg
b ggct
c ccga
I wish to create individual text files for each row, where named the file is named based on one column and the file contents are based on another column.
I currently have this code:
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
Which creates text files with the values in the 'Name' column for each row. However I am unsure how to write the 'Seq' column to each text file.
You are very close:
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'])
I added the print
statement just to show what each " row
" is; you already key the Name
when creating file_name
, you just need to key Seq
when writing:
OrderedDict([('Name', 'a'), ('Seq', 'atcg')])
OrderedDict([('Name', 'b'), ('Seq', 'ggct')])
OrderedDict([('Name', 'c'), ('Seq', 'ccga')])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.