简体   繁体   English

shutil.move() 仅适用于现有文件夹?

[英]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.我想使用 shutil.move() 函数将一些匹配特定模式的文件移动到新创建的(在 python 脚本中)文件夹,但似乎该函数仅适用于现有文件夹。

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'例如,我在文件夹“/test”中有“a.txt”、“b.txt”、“c.txt”,我想使用 os.txt 在我的 python 脚本中创建一个文件夹“/test/b”。 join() 并将所有 .txt 文件移动到文件夹 '/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)所以shutil.move工作,但不像你期望的那样,而是像一个标准的mv命令:它将每个文件移动到名为“b”的父目录,覆盖每个旧文件,只留下最后一个(非常危险,因为有数据丢失的风险)

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.现在shutil.move将在移动到b时创建文件,因为b是一个目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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