【问题标题】:Write a text file for each row in a csv为csv中的每一行编写一个文本文件
【发布时间】:2020-10-06 06:08:01
【问题描述】:

我有一个格式如下的 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”列写入每个文本文件。

【问题讨论】:

    标签: python csv text write


    【解决方案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”是什么;您在创建file_name 时已经键入了Name,您只需在编写时键入Seq

    OrderedDict([('Name', 'a'), ('Seq', 'atcg')])
    OrderedDict([('Name', 'b'), ('Seq', 'ggct')])
    OrderedDict([('Name', 'c'), ('Seq', 'ccga')])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2019-07-08
      相关资源
      最近更新 更多