我是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'
所以这是不正确的。
我不想对诸如“ \”之类的东西进行硬编码来解决问题,而且我很确定自己也可以简化上面的代码。
您能帮我告诉我我错了吗?
答案 0 :(得分:0)
您的问题是这一行:
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)