【问题标题】:How to go through a list of files如何浏览文件列表
【发布时间】:2016-09-10 00:05:11
【问题描述】:

我正在尝试制作一个脚本,该脚本将一次运行一个单词列表,并将其插入脚本的 3 个区域,然后重新开始。然后当它到达列表的末尾时停止。

wordlist = ['word1','word2','word3']

贯穿word1

csvinput = 'mainfile.csv'

reader = csv.reader(open(r'{0}'.format(csvinput)), delimiter=',') 
filtered = filter(lambda p: 'word1' == p[6], reader) 
csv.writer(open(r"word1\word1.csv",'w', newline = ''),delimiter=',').writerows(filtered)
time.sleep(0.1) 

然后重新开始,但在word2 等..直到它到达终点

【问题讨论】:

    标签: python list loops csv


    【解决方案1】:

    你的意思是这样吗?

    csvinput = 'mainfile.csv'
    reader = csv.reader(open(r'{0}'.format(csvinput)), delimiter=',')
    
    for word in wordlist:
        filtered = filter(lambda p: word == p[6], reader) 
        csv.writer(open("{}\{}.csv".format(word, word),'w', newline = ''),delimiter=',').writerows(filtered)
        time.sleep(0.1)
    

    一些关于循环值的一般文档:https://docs.python.org/3.4/tutorial/classes.html#iterators https://docs.python.org/3.4/tutorial/datastructures.html#looping-techniques

    【讨论】:

    • 谢谢!迭代器也是我一直在寻找的。唯一的问题是它似乎停止在word1 之后插入数据,但它确实创建了文件。我认为这可能是filter 的问题
    • 你有 mainfile.csv 的例子吗?可能有更简单的方法来实现结果。
    • 它现在可以工作了!我不得不将 csvinputreader 移动到你的循环中
    • 很高兴它正在工作,但我觉得它会非常低效 - 基本上你正在阅读整个文件三遍。这可能不是您需要担心的事情,但如果您开始扩大规模,肯定会开始产生影响。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2022-01-08
    • 2019-03-18
    • 2019-03-23
    • 2023-03-25
    相关资源
    最近更新 更多