python - 将文件搜索到目录/兼容的 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'
所以这是不正确的。
我不想硬编码诸如“\”之类的东西来解决问题,而且我很确定我也可以简化上面的代码。
你能帮我在这里告诉我我错了吗?
解决方案
你的问题是这一行:
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)
推荐阅读
- flutter - 如何更新内置于 FutureBuilder 中的小部件状态
- reactjs - 如何根据 url 参数动态创建 React 组件?
- r - 在 R 中生成子序列
- reactjs - 反应弹出窗口在 iOS 上的工作方式与桌面不同
- c++ - 未找到 Magick++.h 标头
- docker - 在 MacOS 上让容器使用主机的代理
- python - 我如何在 python 中并行运行 2 个线程
- mysql - 如何设置我的 nginx 文件以连接到我的服务器?
- google-bigquery - 在 BigQuery 中,将对象的字符串化数组转换为非字符串化
- model-view-controller - 第一次使用 MVC