python - 尝试使用 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
都丢失了。一开始,文件就在那里。我想在这里获得一些见解;
- 是否
os.shutil.move
将文件移动到临时文件夹而不是目标文件夹之类的地方? - 在任何情况下是否
os.shutil.move
会从源中删除文件? - 有什么方法可以测试我的脚本以找出丢失文件的潜在原因?
非常感谢任何帮助或建议?
解决方案
已经很晚了,但人们不明白操作员的问题。如果将文件移动到不存在的文件夹中,该文件似乎会变成压缩的二进制文件并永远丢失。它发生在我身上两次,一次在 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
推荐阅读
- node.js - ReactJS + Axios + NodeJS - _id:无法读取 null 的属性“ownerDocument”
- javascript - 创建具有不同文本的多个页面以使用 javascript 打印
- swift - 这个 Swift 属性是被覆盖还是隐藏?
- variables - 如何使用 SCSS 变量设置明暗模式
- android - 从 Android 应用程序向 API URL (localhost) 发送和检索数据
- vhdl - 用于发送串行字节的简单 VHDL 测试台程序?
- python - 如何替换文本文件中的多行?
- python - + 不支持的操作数类型:'int' snd 'str'
- tensorflow-serving - 提高 tensorflow-serving 中非常大的输入/输出图像的 io 性能
- django - 重定向按钮到 django admin auth 视图