首页 > 解决方案 > 尝试使用 python shutil.move 移动文件时丢失文件

问题描述

我的源文件夹中有 120 个文件,我需要将它们移动到新目录(目标)。目标made在我编写的函数中,基于string文件名中的。例如,这是我使用的函数。

path   ='/path/to/source'
dropbox='/path/to/dropbox'
files = = [os.path.join(path,i).split('/')[-1] for i in os.listdir(path) if i.startswith("SSE")]
sam_lis      =list()
for sam in files:
    sam_list =sam.split('_')[5]
    sam_lis.append(sam_list)
    sam_lis  =pd.unique(sam_lis).tolist()

# Using the above list
ID  = sam_lis

def filemover(ID,files,dropbox):
    """
    Function to move files from the common place to the destination folder
    """
    for samples in ID:
        for fs in files:
            if samples in fs:
                desination = dropbox  + "/"+ samples + "/raw/"
                if not os.path.isdir(desination):
                    os.makedirs(desination)
        for rawfiles in fnmatch.filter(files, pat="*"):
            if samples in rawfiles:
                shutil.move(os.path.join(path,rawfiles), 
                            os.path.join(desination,rawfiles))

在函数中,我根据从文件列表中派生的 ID 创建目标文件夹。当我第一次尝试运行它时,它把我扔了FILE NOT exists error。但是,后来当我检查源文件时,所有以开头的文件SSE都丢失了。一开始,文件就在那里。我想在这里获得一些见解;

  1. 是否os.shutil.move将文件移动到临时文件夹而不是目标文件夹之类的地方?
  2. 在任何情况下是否os.shutil.move会从源中删除文件?
  3. 有什么方法可以测试我的脚本以找出丢失文件的潜在原因?

非常感谢任何帮助或建议?

标签: pythonshutil

解决方案


已经很晚了,但人们不明白操作员的问题。如果将文件移动到不存在的文件夹中,该文件似乎会变成压缩的二进制文件并永远丢失。它发生在我身上两次,一次在 git bash 中,另一次在 Python 中使用 shutil.move。我记得当您的 shutil.move 目标指向文件夹而不是完整文件路径的副本时,python 就会发生。

例如,如果您运行下面的代码,将发生与操作描述类似的情况:

src_folder = r'C:/Users/richa'
dst_folder = r'C:/Users/richa/data_images'
file_names = glob(r'C:/Users/richa/*.jpg')

for file in file_names:
    file_name = os.path.basename(file)
    shutil.move(os.path.join(src_folder, file_name), dst_folder)

请注意,else块中的 dst_folder 只是一个文件夹。它应该是 dst_folder + file_name。这将导致 Op 在他的问题中描述的内容。我在此处的链接上找到了类似的内容,并更详细地说明了问题所在:File move error with Python


推荐阅读