简体   繁体   中英

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 . 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:

os.mkdir

fpath = '~/Desktop/PDF_extracted'
if not os.path.exists(fpath):
    os.mkdir(fpath)

pathlib.Path.mkdir

from pathlib import Path 

fpath = '~/Desktop/PDF_extracted'
path_obj = Path(fpath)
if not path_obj.exists():
    path_obj.mkdir()

Side note:

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.

Additional resources:

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")
  1. You are in the current directory indicated by '.'period sign and if you want to know your absolute path directory.
  2. You make 'new_folder' by 'os.mkdir' code
  3. Assuming that you have 'test' folder in your current directory '~/Desktop' containing 'file.txt' file to move.
  4. 'shutil.move' will help you to move 'file.txt' file from '~/Desktop/test/' folder to '~/Desktop/new_folder' 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM