[英]How to open files when subdirs name and file names match
我有這樣的文件結構
\dir1
\subdir1
-file1.txt
-file2.txt
\subdir3
-file2.txt
\dir2
\subdir1
-file1.txt
\subdir2
-file2.txt
當dir2
subdirs
名稱與dir1
中的名稱匹配時,我想使用dir1
作為參考目錄並在dir2
中打開文件。 所以基本上在\dir1\subdir1\file1.txt
和\dir2\subdir1\file1.txt
中打開file1.txt
並且也匹配文件名。
我可以遍歷subdirs
,但找不到比較它們的邏輯
for path, subdirs, files in os.walk(path_to_json) :
for file in subdirs :
print (file)
我們應該怎么做?
您只需將 dir1 替換為 dir2 即可創建路徑,如果有這樣的文件,則打開這兩個文件。
import os
path = r"C:....dir1"
files_dir1 = []
# We make a list of all files in the directory dir1.
for root, dirs, files in os.walk(path):
for file in files:
files_dir1.append(os.path.join(root, file))
for name in files_dir1:
name_dir2 = name.replace('dir1', 'dir2', 1)
# Open files when a file with a new path exists.
if os.path.isfile(name_dir2):
with open(name, 'r') as f:
print(name, f.read())
with open(name_dir2, 'r') as f:
print(name_dir2, f.read())
你可以嘗試這樣的事情:
from pathlib import Path
for file_1 in Path('dir1').rglob('*.*'):
file_2 = Path('dir2', *file_1.parts[1:])
if file_2.exists():
print(str(file_1))
print(str(file_2))
如果您只想將 go 用於txt
-文件,則將.rglob('*.*')
更改為.rglob('*.txt')
。 當有沒有擴展名的文件時,您可以這樣做:
for file_1 in Path('dir1').rglob('*'):
if file_1.is_dir():
continue
file_2 = Path('dir2', *file_1.parts[1:])
if file_2.exists():
print(str(file_1))
print(str(file_2))
如果您只想要第一個子級別的文件(正好是一個子目錄深度),那么您可以嘗試:
for file_1 in Path('dir1').glob('*/*.*'):
file_2 = Path('dir2', *file_1.parts[1:])
if file_2.exists():
print(str(file_1))
print(str(file_2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.