I was trying to move the files from a folder to another one on my local machine using 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. You can do so using os.mkdir or 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.
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. I need to change it into a Microsoft type such as ./../Desktop
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.