[英]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.