【问题标题】:Loop list and open file if found循环列表并打开文件(如果找到)
【发布时间】:2013-05-16 03:52:13
【问题描述】:

不知道从哪里开始...我知道如何读取 csv 文件,但如果我在同一目录中有一堆文件,如何根据它们是否在列表中读取它们。例如,诸如...的列表

l= [['file1.csv','title1','1'], ['file2.csv','title2','1'],['file3.csv','title3','1']]

即使目录中的文件最多为“file20.csv”,我如何才能仅获取这 3 个文件。 我可以以某种方式遍历列表并使用 if 语句检查文件名并在找到时打开文件吗?

【问题讨论】:

  • 您想使用哪种编程语言?

标签: python loops csv python-2.x


【解决方案1】:
for filedesc in l: #go over each sublist in l
    fname, ftitle, _ = filedesc #unpack the information contained in it
    with open(fname) as f: #open the file with the appropriate name
        reader = csv.reader(f) #create reader of that file
        #go about bussiness

【讨论】:

  • 谢谢@HennyH,但我可以问一下,我需要解压缩所有信息还是不能按第一列中出现的文件名搜索,即。文件 1.csv.
【解决方案2】:

一个更新的帖子,因为我已经很接近这个了......

lfiles= []
csvfiles=[]
for row in l:
    lfiles= row[0]      #This reads in just the filesnames from list 'l' 
with open(lfiles) as x:
    inread = csv.reader(x)
    for i in x:
        print i

这会打印读入的文件中的所有内容,但现在我想在特定列等于某个值时将“csvfiles”(一个空列表)附加到一行。 大概是这样的……????

for i in x:
    for line in i:
        if line= 'ThisThingAppears5Times':
            csvfiles.append(line)  # and now the 5 lines are in a 2dlist

当然这不起作用但关闭?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多