【问题标题】:how to create file txt filename from file csv with python 2.7如何使用 python 2.7 从文件 csv 创建文件 txt 文件名
【发布时间】:2017-02-11 23:03:16
【问题描述】:
import csv
with open("HORSES.csv") as f:
for row in csv.reader(f):   
    # Number of pages plus one
    for horse in row:
        print (horse)
with open("%s.txt" % horse, "w") as f:
            f.close()

此内容文件 horses.csvwest,usa,asia,black。输出操作系统很好,但是对于创建 .txt 文件仅 black.txt 文件结尾 horses.csv 不从列表 pd csv 文件创建文件 txt,如何使用来自列表文件 horses.csv 的文件名创建 .txt 文件,就像这样 west.txt usa.txt asia.txt black.txt

【问题讨论】:

    标签: python python-2.7 csv


    【解决方案1】:

    您的最后一个 with 语句不是循环的一部分,因此您只会获得存储在 horse 中的最后一个值。

    如果您想要多个 .txt 文件,请将它们放在一个循环中并一次创建一个:

    import csv
    
    Horse_types = []
    
    with open("HORSES.csv") as f:
        for row in csv.reader(f):   
            for horse in row:
                print (horse)
                Horse_types.append(horse)
    
    for ht in Horse_types:
        with open("%s.txt" % ht, "w") as f:
            # More stuff here?
            f.close()
    

    【讨论】:

    • 谢谢。,你能再次帮助我完整的代码吗?上面带有 beatifulsoup 的脚本代码部分,因为我总是出错
    猜你喜欢
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2019-06-19
    • 2017-03-04
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多