繁体   English   中英

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

[英]shutil.move() only works with existing folder?

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

例如,我在文件夹“/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'

任何建议表示赞赏!

问题在于,当您创建目标路径变量名称时:

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

路径不存在 所以shutil.move工作,但不像你期望的那样,而是像一个标准的mv命令:它将每个文件移动到名为“b”的父目录,覆盖每个旧文件,只留下最后一个(非常危险,因为有数据丢失的风险)

如果目录不存在,首先创建目录:

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

现在shutil.move将在移动到b时创建文件,因为b是一个目录。

暂无
暂无

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

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