【问题标题】:Move only files from list仅从列表中移动文件
【发布时间】:2018-10-19 19:21:27
【问题描述】:

我正在尝试从一个目录创建一个列表,更改名称以匹配另一个命名约定,并使用该列表引用不同目录中的文件以移动到另一个目录。我已经做到了这一点,但 shutil.move() 正在移动整个目录,而不是在列表中搜索匹配的文件名。

我不确定如何进行,任何帮助将不胜感激!

#Goal is to create list from the reference folder, 
#change names in list to match naming convention in the source folder,
#and move only those files to the destination folder. 

import os 
import shutil

r = input("Reference Folder")
s = input("Source Folder")
d = input("Destination folder")
os.chdir(r)

if not os.path.exists(d):
    os.mkdir(d)
#creating filelist from reference folder
filelist = []
for root, dirs, files in os.walk(".", topdown = False):
    for file in files:
        filelist.append(file)

#changing filelist to match source folder's naming convention. 

os.chdir(s)

filelist = [f.replace('filling_mask', 'tex') for f in filelist]

print("Moving these")

print(filelist)

for t in filelist:
    shutil.move(s, d) 

【问题讨论】:

  • 你的变量名不是很具描述性(你应该改变它们),但它不应该是t你试图移动,而不是s
  • 最后一行不是shutil.move(t, d)吗?

标签: python shutil


【解决方案1】:

好的,这里是给你的提示,而不是:

for t in filelist:
    shutil.move(s, d) 

这样做:

for t in filelist:
    print('From: {}\nTo: {}'.format(s,d))
    break
    #shutil.move(s,d)

现在这里的技巧是确保文件位置存在并且目标文件夹也存在。通过使用 print 语句而不是实际移动内容,您可以无休止地调试它。

提示:filelist.append(file) 仅附加文件名。您还需要包含路径。一种方法是使用 os.path.join (os.path.join(root, file))。现在,当将该文件移动到目标文件夹时,您需要剥离根目录并使用目标进行更改。

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2022-08-16
    • 2013-11-20
    相关资源
    最近更新 更多