[英]Move files one by one to newly created directories for each file with Python 3
我擁有的是一個初始目錄,其中 D:\BBS\file.x 中有一個文件,工作目錄 D:\ 中有多個.txt 文件
我要做的是復制文件夾 BBS 及其內容並按數字遞增其名稱,然后將每個現有的.txt 文件復制/移動到新創建的目錄以使其成為 \BBS1、\BBS2、...、BBSn (取決於 txt 的數量)。
之前和之后的視覺示例:
\WorkFolder 的初始視圖
\WorkFolder 的所需視圖
現在,我只創建了一個新目錄並在其中移動 txt,但一次完成,而不是我想要的。 這是我的代碼:
from pathlib import Path
from shutil import copy
import shutil
import os
wkDir = Path.cwd()
src = wkDir.joinpath('BBS')
count = 0
for content in src.iterdir():
addname = src.name.split('_')[0]
out_folder = wkDir.joinpath(f'!{addname}')
out_folder.mkdir(exist_ok=True)
out_path = out_folder.joinpath(content.name)
copy(content, out_path)
files = os.listdir(wkDir)
for f in files:
if f.endswith(".txt"):
shutil.move(f, out_folder)
如前所述,我懇請協助將文件一一增加和復制到新創建的目錄中。
一般用python技能不多。 Python3 OS Windows 提前致謝
現在,我明白你想要完成什么。 我認為您只需遍歷文本文件並為每個文件復制 BBS 文件夾就可以很容易地做到這一點。 之后,您移動當前所在的文件。 為了獲取folder_num
,如果名稱始終為TextXX.txt
模式,您可能只能訪問特定索引處的文件名字符(例如f[4:6]
)。 如果前綴“Text”可能有所不同,則使用如下示例中的正則表達式會更穩定。
此外,function shutil.copytree
復制一個目錄及其子目錄。
import re
import shutil
from pathlib import Path
wkDir = Path.cwd()
src = wkDir.joinpath('BBS')
for f in os.listdir(wkDir):
if f.endswith(".txt"):
folder_num = re.findall(r"\d+", f)[0]
target = wkDir.joinpath(f"{src.name}{folder_num}")
# copy BBS
shutil.copytree(src, target)
# move .txt file
shutil.move(f, target)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.