打印语句在我的文件管理系统中没有响应
Print statement not responding in my filemanagement system
我有 2 个文件夹:源和目标。这些文件夹中的每一个都有 3 个名为 A、B 和 C 的子文件夹。Source 中的 3 个子文件夹都包含多个文件。 Destination 中的 3 个子文件夹(还)是空的。
我需要全部的完整路径,因为我的目标是在目标 A、B 和 C 中覆盖来自源 A、B 和 C 的文件。
为什么我的两个打印语句没有打印任何东西?我的错误为零。
import os
src = r'c:\data\AM\Desktop\Source'
dst = r'c:\data\AM\Desktop\Destination'
os.chdir(src)
for root, subdirs, files in os.walk(src):
for f in subdirs:
subdir_paths = os.path.join(src, f)
subdir_paths1 = os.path.join(dst, f)
for a in files:
file_paths = os.path.join(subdir_paths, a)
file_paths1 = os.path.join(subdir_paths1, a)
print(file_paths)
print(file_paths1)
问题
如jasonharper said in 、
You are misunderstanding how os.walk()
works. The files returned in files
are in the root
directory; you are acting as if though they existed in each of the subdirs
directories, which are actually in root
themselves.
没有打印任何内容的原因是,在第一次迭代中,files
为空,因此未输入 for a in files
。然后在接下来的迭代中(其中 root
分别为 A、B 和 C),subdirs
为空,因此未输入 for f in subdirs
。
解决方案
事实上你完全可以忽略subdirs
。而是走当前目录,加入 src
/dst
+ root
+ a
:
import os
src = r'c:\data\AM\Desktop\Source'
dst = r'c:\data\AM\Desktop\Destination'
os.chdir(src)
for root, subdirs, files in os.walk('.'):
src_dir = os.path.join(src, root)
dst_dir = os.path.join(dst, root)
for a in files:
src_file = os.path.join(src_dir, a)
dst_file = os.path.join(dst_dir, a)
print(src_file)
print(dst_file)
输出应该在 src
/dst
和 root
之间有一个额外的点目录。如果有人能告诉我如何摆脱它,我洗耳恭听。
我有 2 个文件夹:源和目标。这些文件夹中的每一个都有 3 个名为 A、B 和 C 的子文件夹。Source 中的 3 个子文件夹都包含多个文件。 Destination 中的 3 个子文件夹(还)是空的。
我需要全部的完整路径,因为我的目标是在目标 A、B 和 C 中覆盖来自源 A、B 和 C 的文件。
为什么我的两个打印语句没有打印任何东西?我的错误为零。
import os
src = r'c:\data\AM\Desktop\Source'
dst = r'c:\data\AM\Desktop\Destination'
os.chdir(src)
for root, subdirs, files in os.walk(src):
for f in subdirs:
subdir_paths = os.path.join(src, f)
subdir_paths1 = os.path.join(dst, f)
for a in files:
file_paths = os.path.join(subdir_paths, a)
file_paths1 = os.path.join(subdir_paths1, a)
print(file_paths)
print(file_paths1)
问题
如jasonharper said in
You are misunderstanding how
os.walk()
works. The files returned infiles
are in theroot
directory; you are acting as if though they existed in each of thesubdirs
directories, which are actually inroot
themselves.
没有打印任何内容的原因是,在第一次迭代中,files
为空,因此未输入 for a in files
。然后在接下来的迭代中(其中 root
分别为 A、B 和 C),subdirs
为空,因此未输入 for f in subdirs
。
解决方案
事实上你完全可以忽略subdirs
。而是走当前目录,加入 src
/dst
+ root
+ a
:
import os
src = r'c:\data\AM\Desktop\Source'
dst = r'c:\data\AM\Desktop\Destination'
os.chdir(src)
for root, subdirs, files in os.walk('.'):
src_dir = os.path.join(src, root)
dst_dir = os.path.join(dst, root)
for a in files:
src_file = os.path.join(src_dir, a)
dst_file = os.path.join(dst_dir, a)
print(src_file)
print(dst_file)
输出应该在 src
/dst
和 root
之间有一个额外的点目录。如果有人能告诉我如何摆脱它,我洗耳恭听。