[英]Lost files while tried to move files using python shutil.move
我的源文件夹中有 120 个文件,我需要将它们移动到新目录(目标)。 根据文件名中的string
,目标是在我编写的 function 中made
的。 比如这里是我用的function。
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))
在 function 中,我根据从文件列表派生的 ID 创建目标文件夹。 当我第一次尝试运行它时,它向我抛出了FILE NOT exists error
。 但是,后来当我检查源代码时,所有以SSE
开头的文件都丢失了。 一开始,文件就在那里。 我想在这里获得一些见解;
os.shutil.move
是否将文件移动到临时文件夹而不是目标文件夹之类的地方?os.shutil.move
在任何情况下是否会从源中删除文件?非常感谢任何帮助或建议?
shutil.move 不会删除您的文件,如果由于任何原因您的文件未能移动到给定位置,请检查您的代码存储的目录,您的文件最有可能存储在那里的“+”文件夹。
已经很晚了,但人们不明白操作员的问题。 如果将文件移动到不存在的文件夹中,该文件似乎会变成压缩的二进制文件并永远丢失。 它发生在我身上两次,一次在 git bash 中,另一次在 Python 中使用 shutil.move。 我记得 python 发生在您的 shutil.move 目标指向文件夹而不是完整文件路径的副本时。
例如,如果您运行下面的代码,将发生与操作描述类似的情况:
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 在他的问题中描述的内容。 我在此处的链接上找到了类似的内容,并更详细地说明了问题所在: Python 的文件移动错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.