【问题标题】:Using a reference list to find specific files by name使用参考列表按名称查找特定文件
【发布时间】:2016-05-05 18:16:38
【问题描述】:

我有从存储在变量中的 csv 中提取的文件名列表,我想在某个目录中搜索该文件名,请参阅下面将此列表提取到变量名文件名。如果找到我想对匹配的文件一个一个地执行某个操作。

#Python 3.5, Pandas 0.17.1
#Reading in list with characteristics of files
index = pd.read_csv('INDEX.csv',usecols = ['Filenumber','Province'])
#Automating extraction of column filename on basis of province and full rows
province = index[index.Province == 'MG']
filenames = province['Filenumber']

到目前为止,我还没有找到任何解决此问题的方法。我是 Python 新手,因此非常感谢任何朝着正确方向的推动,无论是以解决方案或参考材料的形式来阅读这些类型的操作。

总结:

使用具有文件名称的变量文件名(减去文件类型 (.csv)),我想在一个目录/文件夹中找到具有这些名称的文件。然后(或在搜索文件期间)对每个文件执行特定操作。

【问题讨论】:

    标签: python csv search pandas glob


    【解决方案1】:

    这是你要找的吗?

    import os
    
    filenames =['testfile1','testfile2']
    
    for file in filenames:
        if os.path.isfile(file+'.csv'):
            print "File "+ file + ".csv exists."
        else:
            print "File "+ file + ".csv does not exist."
    

    编辑:以下是python 3.x(未经测试,因为我没有):

    import os
    
    filenames =['testfile1.csv','testfile2.csv']
    
    for file in filenames:
        if os.path.isfile(file):
            print("File exists.")
        else:
            print("File does not exist.")
    

    【讨论】:

    • 这会导致以下错误: Traceback (last recent call last): File "C:\Users\code.py", line 35, in if os.path.isfile(file +'.csv'): TypeError: ufunc 'add' 不包含签名匹配类型的循环 dtype('
    • 对不起,我正在使用 Python 2.7,还没有看到您似乎在使用 python 3.x。您必须使打印命令和字符串操作适应 python 3.7。我在上面附上了一个更简单的版本,应该在 3.7 中工作
    • 能够让它工作。这里的主要问题是,在我的原始代码中,变量文件名不包含作为字符串的实际文件名。我无法使用您的解决方案中描述的语法。但是,将文件名中的名称转换为字符串并添加“.csv”可以使代码正常工作。因此:文件名 = 省 ['Filenumber'].astype(str) + '.csv'。然后使用您的解决方案。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多