简体   繁体   中英

shutil.move() only works with existing folder?

I would like to use the shutil.move() function to move some files which match a certain pattern to a newly created(inside python script)folder, but it seems that this function only works with existing folders.

For example, I have 'a.txt', 'b.txt', 'c.txt' in folder '/test', and I would like to create a folder '/test/b' in my python script using os.join() and move all .txt files to folder '/test/b'

import os 
import shutil
import glob

files = [file for file in glob.glob('./*.txt')] #assume that we in '/test' 

for f in files:
    shutil.move(f, './b') #assume that './b' already exists

#the above code works as expected, but the following not:

import os
import shutil
import glob

new_dir = 'b'
parent_dir = './'
path = os.path.join(parent_dir, new_dir)

files = [file for file in glob.glob('./*.txt')]

for f in files:
    shutil.move(f, path)

#After that, I got only 'b' in '/test', and 'cd b' gives:
#[Errno 20] Not a directory: 'b'

Any suggestion is appreciated!

the problem is that when you create the destination path variable name:

path = os.path.join(parent_dir, new_dir)

the path doesn't exist . So shutil.move works, but not like you're expecting, rather like a standard mv command: it moves each file to the parent directory with the name "b", overwriting each older file, leaving only the last one (very dangerous, because risk of data loss)

Create the directory first if it doesn't exist:

path = os.path.join(parent_dir, new_dir)
if not os.path.exists(path):
   os.mkdir(path)

now shutil.move will create files when moving to b because b is a directory.

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