[英]How to open files when subdirs name and file names match
I have file structure like this我有这样的文件结构
\dir1
\subdir1
-file1.txt
-file2.txt
\subdir3
-file2.txt
\dir2
\subdir1
-file1.txt
\subdir2
-file2.txt
I want to use dir1
as reference directory and open file in dir2
when dir2
subdirs
names match to that one in dir1
.当
dir2
subdirs
名称与dir1
中的名称匹配时,我想使用dir1
作为参考目录并在dir2
中打开文件。 So basically open file1.txt
in both \dir1\subdir1\file1.txt
and \dir2\subdir1\file1.txt
and also match the file names as well.所以基本上在
\dir1\subdir1\file1.txt
和\dir2\subdir1\file1.txt
中打开file1.txt
并且也匹配文件名。
I can walk through the subdirs
but cannot find the logic to compare them我可以遍历
subdirs
,但找不到比较它们的逻辑
for path, subdirs, files in os.walk(path_to_json) :
for file in subdirs :
print (file)
How can we do this?我们应该怎么做?
how to open files that match a pattern in a subdirectory 如何打开与子目录中的模式匹配的文件
You can create a path simply by replacing dir1 with dir2 and if there is such a file, then open both files.您只需将 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())
You could try something like this:你可以尝试这样的事情:
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))
If you only want to go for txt
-files then change .rglob('*.*')
to .rglob('*.txt')
.如果您只想将 go 用于
txt
-文件,则将.rglob('*.*')
更改为.rglob('*.txt')
。 When there are files without an extension you could do:当有没有扩展名的文件时,您可以这样做:
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))
If you only want the files from the first sublevel (exactly one subdir-depth) then you could try:如果您只想要第一个子级别的文件(正好是一个子目录深度),那么您可以尝试:
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.