我想使用 Shutil.move() 函数将一些与特定模式匹配的文件移动到新创建的(Python 脚本内)文件夹,但似乎该函数仅适用于现有文件夹。
例如,我在文件夹“/test”中有“a.txt”、“b.txt”、“c.txt”,我想使用 os.path 在我的 python 脚本中创建一个文件夹“/test/b”。 join() 并将所有 .txt 文件移动到文件夹“/test/b”
import os
import shutil
import glob
files = 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 = glob.glob('./*.txt')
for f in files:
shutil.move(f, path)
#After that, I got only 'b' in …Run Code Online (Sandbox Code Playgroud)