我正在尝试使用python来自动化将测试结果文件移动到新创建的文件夹的手动过程。
简单地说,我们测试的每个部分都会吐出5个文件,3x.txt文件,1x.PDF和1x.ZMP文件。我们有一个由数百个这样的文件组成的不断增长的文件夹。
所有这些文件的序列号都是TSS-XXXX-XXXX例如:
- 2354-472_5000_POB_EXYZ_small_L48_2354-472-03-TSS-209-0021_pwr.pdf
- 2354-472_5000_POB_EXYZ_small_L48_2354-472-03-TSS-209-0021_chr.txt
- 2354-472_5000_POB_EXYZ_small_L48_2354-472-03-TSS-209-0021_fet.txt
- 2354-472_5000_POB_EXYZ_small_L48_2354-472-03-TSS-209-0021_hdr.txt
- 2354-472-03-TSS-209-0021-zmp
我的目标是创建一个脚本,搜索TSS-XXXX-XXXX编号,然后将所有这些部件移动到一个新文件夹中,该文件夹是根据TSS编号创建的。
因此,文件:2354-472_5000_POB_EXYZ_small_L48_2354-472-03-TSS-209-0021_pwr.pdf将被复制/移动到名为TSS-209-0022的文件夹中
我只真正接触过python几次,我找不到任何其他线程有这样的解决方案,所以任何帮助都将不胜感激。
谢谢!
我试过了:
import os, shutil
src = r"C:XYZ L48"
dest = r"C:XYZ L48"
for dirpath, dirs, files in os.walk(src):
for file in files:
if not file.endswith('.'):
Dir = file.split("TSS")[0]
newDir = os.path.join(dest, Dir)
if (not os.path.exists(newDir)):
os.mkdir(newDir)
shutil.move(os.path.join(dirpath, file), newDir)
但这并没有得到想要的结果,它四处移动文件,但没有按TSS序列号移动
此代码将遍历SRC
中的所有文件,如果file name
包含TSS
,它将解压缩TSS-XXXX-XXXX
,然后检查DST
文件夹中是否存在TSS-XXXX-XXXX
文件夹(如果不存在,它将创建文件夹(,然后将文件从SRC
移到DSTTSS-XXXX-XXXX
如果已经存在,则跳过文件
import os
import shutil
SRC = r"The Source Path"
DST = r"The Destination Path"
# create DST path
if not os.path.isdir(DST):
os.makedirs(DST, exist_ok=True)
# loop on all files and get the folder name that each file is supposed to move to
for file_name in os.listdir(SRC):
# if it is one of the files we are looking for
if "TSS" in file_name:
# extract folder name
folder_name = "TSS" + file_name.split("TSS")[-1][:10]
# create folder if it doesn't exist
if not os.path.isdir(DST + "\" + folder_name):
os.mkdir(DST + "\" + folder_name)
# if file doesn't exist copy the file
if not os.path.isfile(DST + "\" + folder_name + "\" + file_name):
# copy the file with the metadata
shutil.copy2(SRC + "\" + file_name, DST + "\" + folder_name + "\")
如果已经存在,则覆盖文件
import os
import shutil
SRC = r"The Source Path"
DST = r"The Destination Path"
# create DST path
if not os.path.isdir(DST):
os.makedirs(DST, exist_ok=True)
# loop on all files and get the folder name that each file is supposed to move to
for file_name in os.listdir(SRC):
# if it is one of the files we are looking for
if "TSS" in file_name:
# extract folder name
folder_name = "TSS" + file_name.split("TSS")[-1][:10]
# create folder if it doesn't exist
if not os.path.isdir(DST + "\" + folder_name):
os.mkdir(DST + "\" + folder_name)
# if file exists remove it
if os.path.isfile(DST + "\" + folder_name + "\" + file_name):
os.remove(DST + "\" + folder_name + "\" + file_name)
# copy the file with the metadata
shutil.copy2(SRC + "\" + file_name, DST + "\" + folder_name + "\")