[英]python remove file from one directory to another
I was trying to move the files from a folder to another one on my local machine using shutil.move
.我试图使用
shutil.move
将文件从一个文件夹移动到本地计算机上的另一个文件夹。 But I kept getting this error:但我一直收到这个错误:
I think it occurs because the destination does not exist because it is exactly where I going to move it.我认为它发生是因为目的地不存在,因为它正是我要移动它的地方。 So how can I make the file existent before moving it there?
那么在将文件移到那里之前如何使文件存在呢?
Note: here is my codes:注意:这是我的代码:
import os
import shutil
path = '.\PDF_data\PDF'
record = pd.read_csv('~/Desktop/sec_results1.csv')
for file in tqdm(record['ID Number']):
pdf = path + '/' + file + '.pdf'
if os.path.exists(pdf):
shutil.move(pdf, '~/Desktop/PDF_extracted' + '/' + file + '.pdf')
If '~/Desktop/PDF_extracted'
isn't a directory that already exists, you'll have to create it prior to moving files there.如果
'~/Desktop/PDF_extracted'
不是一个已经存在的目录,您必须在将文件移动到那里之前创建它。 You can do so using os.mkdir or pathlib.Path.mkdir .您可以使用os.mkdir或pathlib.Path.mkdir这样做。
The following is how you could accomplish this with either one:以下是您如何使用其中任何一个来完成此操作:
fpath = '~/Desktop/PDF_extracted'
if not os.path.exists(fpath):
os.mkdir(fpath)
from pathlib import Path
fpath = '~/Desktop/PDF_extracted'
path_obj = Path(fpath)
if not path_obj.exists():
path_obj.mkdir()
Working with filepath's can be tricky so I would definitely recommend looking into some of os
and especially pathlib
's filepath manipulation methods, they make life a lot easier and will greatly reduce confusion when performing tasks like this.使用文件路径可能很棘手,所以我肯定会建议研究一些
os
,尤其是pathlib
的文件路径操作方法,它们使生活变得更加轻松,并且在执行此类任务时会大大减少混淆。
import os
import shutil
path = '.'
print(os.path.abspath(path))
os.mkdir("new_folder")
old_folder = "test"
shutil.move("~/Desktop/test/file.txt", "new_folder")
I did it on Windows 10 so ~\Desktop
can not be recognized.我在 Windows 10 上做的,所以
~\Desktop
不能被识别。 I need to change it into a Microsoft type such as ./../Desktop
.我需要将其更改为 Microsoft 类型,例如
./../Desktop
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.