嵌套 for 循环只对列表的最后一项执行
Nested for loop only executing for last item of list
我正在尝试从文本文件中读取目录列表,并使用它来将目录复制到新位置。我下面的代码似乎只完成了列表最后一项的“#Perform copy or move files”循环。有人可以指出我的方向吗?
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()
...
我正在尝试从文本文件中读取目录列表,并使用它来将目录复制到新位置。我下面的代码似乎只完成了列表最后一项的“#Perform copy or move files”循环。有人可以指出我的方向吗?
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()
...