Python 嵌套for循环仅对列表的最后一项执行
我试图从文本文件中读取目录列表,并使用该列表将目录复制到新位置。下面的代码似乎只完成了列表最后一项的“#执行复制或移动文件”循环。有人能告诉我为什么吗Python 嵌套for循环仅对列表的最后一项执行,python,nested-loops,Python,Nested Loops,我试图从文本文件中读取目录列表,并使用该列表将目录复制到新位置。下面的代码似乎只完成了列表最后一项的“#执行复制或移动文件”循环。有人能告诉我为什么吗 import os import shutil operation = 'copy' # 'copy' or 'move' text_file = open('C:\User\Desktop\CopyTrial.txt', "r") lines = text_file.readlines() for line in lines:
import os
import shutil
operation = 'copy' # 'copy' or 'move'
text_file = open('C:\User\Desktop\CopyTrial.txt', "r")
lines = text_file.readlines()
for line in lines:
new_file_name = line[47:]
root_src_dir = os.path.join('.',line)
root_target_dir = os.path.join('.','C:\User\Desktop' + new_file_name)
# Perform copy or move files.
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_target_dir)
if not os.path.exists(dst_dir):
os.mkdir(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
if operation is 'copy':
shutil.copy(src_file, dst_dir)
elif operation is 'move':
shutil.move(src_file, dst_dir)
text_file.close()
readlines()
返回的行包括尾随的换行符,但从中创建文件名时不会删除这些换行符。它适用于最后一行的原因是您的文件没有以换行符结尾
使用rstrip()
删除尾随空格
for line in lines:
line = line.rstrip()
...
您是指
行中的最后一行行吗?请尝试打印根目录并确保其中包含要复制的文件。当您可以从命令提示符执行递归目录复制时,为什么要使用Python执行此操作?@Barmar是的,这是正确的,代码仅对行中的最后一行行完全有效。如果我在第一个for循环中打印root\u src\u dir
,它会打印每一行的目录,但如果在第二个for循环中打印,它只打印行中最后一行的目录,这意味着os.walk()
没有找到任何要处理的内容。