首页 > 解决方案 > 将文件搜索到目录/兼容的 Unix/Windows

问题描述

我是 Python 的初学者,并尝试使用 os 模块来查找和聚合给定文件夹中的所有文件,给定一个关键字,例如“example”。

根据我到目前为止发现的内容,这是我的代码:

def import_files_list(path, key_word):
files = []
for i in os.listdir(path):
    if os.path.isfile(os.path.join(path,i)) and key_word in i:
        file_plus_path = path+i
        pprint(file_plus_path)
        files.append(file_plus_path)
return files

actual_dir = os.path.dirname(os.path.realpath(__file__))
wanted_dir = os.path.split(actual_dir)[0]
files_list = import_files_list(wanted_dir, 'example') 
pprint(files_list)

问题是,而不是得到例如:

'C:\\Users\\User\\folder\\example1.csv'

我越来越 :

'C:\\Users\\User\\folderexample1.csv'

所以这是不正确的。

我不想硬编码诸如“\”之类的东西来解决问题,而且我很确定我也可以简化上面的代码。

你能帮我在这里告诉我我错了吗?

标签: python

解决方案


你的问题是这一行:

    file_plus_path = path+i

在这里,您将一个字符串附加到另一个字符串,但它们之间没有任何分隔符。在上一行中,您正确地做到了:os.path.join(path,i).

所以这里有一种纠正方法:

file_plus_path = os.path.join(path,i)
if os.path.isfile(file_plus_path) and key_word in i:
    pprint(file_plus_path)
    files.append(file_plus_path)

推荐阅读