![](/img/trans.png)
[英]Python move all files from multiple subdirectories to different corresponding subdirectories
[英]How can find all files of the same extension within multiple subdirectories and move them to a seperate folder using python?
我已將舊攝像機的內容復制到我的計算機上,在轉移到那里的文件夾中,有 100 多個子文件夾,全部包含我想要的 6 或 7 個文件。 如何能夠搜索所有這些並將所有找到的文件移動到新文件夾? 我對此很陌生,所以歡迎任何幫助。
要找到所有文件,有兩種方法:
例子:
import os
path = 'c:\\location_to_root_folder\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.mpg' in file:
files.append(os.path.join(r, file))
for f in files:
print(f)
import glob
path = 'c:\\location_to_root_folder\\'
files = [f for f in glob.glob(path + "**/*.mpg", recursive=True)]
for f in files:
print(f)
要移動,您可以使用以下 3 種方法中的任何一種,我個人更喜歡 shutil.move:
import os
import shutil
os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
dswdsyd 在這里有正確的答案,盡管您可以更改打印輸出以實際移動文件,如下所示:
import os
path = 'C:\\location_to_root_folder\\'
newpath = 'C:\\NewPath\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.mpg' in file:
files.append(os.path.join(r, file))
for f in files:
os.rename(f, newpath + f.split('/')[-1])
print(f'{f.split('/')[-1]} moved to {newpath}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.