python - 在 Python 中的已更改子目录中查找文件
问题描述
我有一个充满文件名的文本文件。喜欢:
C:\Folder\Subfolder_01\file_1001.csv
C:\Folder\Subfolder_02\file_3030.xls
...
我想检查文件是否仍然存在(这很容易)或者子文件夹的名称是否已更改。一些子文件夹的名称通过在其前面添加一些字符串来更改(以 4 位数字开头,例如C:\Folder\Subfolder_02\file_3030.xls
已更改为C:\Folder\2019 - Subfolder_02\file_3030.xls
)。
我试图用pathlib.glob()
. 可以“手动”为一个特定文件执行此操作,例如
list(file.parent.parent.glob('* - Subfolder_02\file_3030.xls'))
它返回一个带有新文件名的列表。但我未能在围绕glob
with 参数的循环中执行此操作。
这是我到目前为止所得到的,但是由于明显的原因,我尝试将 glob 与其他变量(使用 +)连接失败:
import pathlib
file = pathlib.Path(file_names.txt)
lines=[]
with open(file,'r') as f:
# reading the txt-file line by line
for line in f:
line = line.replace("\r", "").replace("\n", "")
lines.append(line)
for file in lines:
file = pathlib.Path(file)
# check if file exists ...
if file.exists():
print('OK - ' + file.name)
# ... if not, find new location
else:
new_files = list(file.parent.parent.glob('* - ') + file.name)
print(files_files)
解决方案
如果您在原始位置找不到文件,我会将您的顶级目录设置为路径并使用它来全局目录下的文件。**
在 glob 中使用将搜索所有文件夹。
# Set top level directory as desired.
parent_dir = Path('.')
# you can use splitlines() to parse the file into a list
with Path('file_names.txt').open() as f:
files = f.read().splitlines()
for f in files:
orig = Path(f)
# Still in location, no need to look further
if orig.exists():
print(f"{orig.absolute()} is still in place.")
continue
# See if we can find it under parent_dir
matches = [*parent_dir.glob(f"**/{orig.name}")]
if len(matches) > 1:
print("Multiple Matches Found")
for match in matches:
print(f"{orig.absolute()} might be in {match.absolute()}")
推荐阅读
- python - 合并数据框中具有空值的列
- kubernetes - 请求无法到达 Seldon 核心输入转换器
- google-apps-script - onEdit updates top row only after editing multiple rows, but not after copy paste
- python - How can I limit the columns that are seen in a table created with Treeview?
- python - Resizing frameless dialog using QPushButtons
- javascript - 摩卡看不到捆绑的js
- c# - ReSharper 建议将模型类转换为抽象类,我应该这样做吗?
- firebase - How can i dispose or close a listen function from Firestore?
- redux - Redux TypeError: Cannot read property 'list' of undefined
- oauth-2.0 - Issue with access to the Google account by using OAuth