我用 Python 构建的工具有一个小问题。
该工具可以按文件名对文件进行分类,并按每个文件名中的单词创建文件夹,然后将所有文件移动到相应的文件夹。
文件:
09052019_6_filetype1_currenttime_randomnumber.xml
09052019_2_filetype2_currenttime_randomnumber.xml
09052019_9_filetype3_currenttime_randomnumber.xml
09052019_1_filetype3_currenttime_randomnumber.xml
09052019_1_filetype3_currenttime_randomnumber.xml
实际结果:
- filetype1_Status_6(文件夹)
09052019_6_filetype1_currenttime_randomnumber.xml
- filetype2_Status_2(文件夹)
09052019_2_filetype2_currenttime_randomnumber.xml
- filetype3_Status_9(文件夹)
09052019_9_filetype3_currenttime_randomnumber.xml
- filetype3_Status_1(文件夹)
09052019_1_filetype3_currenttime_randomnumber.xml
09052019_1_filetype3_currenttime_randomnumber.xml
代码版本 1.0
#!/usr/bin/python3
# v1.0
# Importing modules
import os
import shutil
import sys
# Path of input and output files
src = input('Input files: ')
dest = input('Destination files: ')
os.chdir(dest)
def classify():
for f in os.listdir(src):
splitname = f.split('_')
status = splitname[1]
topic = splitname[2]
foldername = topic + '_' + 'Status_' + status
if not os.path.exists(foldername):
os.mkdir(foldername)
shutil.move(os.path.join(src, f), foldername)
print('Sorting out files, please wait...')
classify()
print('¡DONE!')
改进
但在 v2.0 中,我想“改进”它一点,只是保持相同的可用性,但将文件名从原始名称更改为“Message_*.xml”,它可以工作,但只能移动一个文件,而不是所有文件其中。
当前结果:
- filetype1_Status_6(文件夹)
- Message_.xml
- filetype2_Status_2(文件夹)
- 消息.xml
- filetype3_Status_9(文件夹)
- Message_.xml
- filetype3_Status_1(文件夹)
- Message_.xml
预期结果:
- filetype1_Status_6(文件夹)
- Message_.xml
- filetype2_Status_2(文件夹)
- 消息.xml
- filetype3_Status_9(文件夹)
- Message_.xml
- filetype3_Status_1(文件夹)
- Message_.xml
- Message_1.xml
代码版本 2.0
#!/usr/bin/python3
# v2.0
# Importing modules
import os
import shutil
import sys
# Path of input and output files
src = input('Input files: ')
dest = input('Destination files: ')
os.chdir(dest)
def classify():
for f in os.listdir(src):
splitname = f.split('_')
status = splitname[1]
topic = splitname[2]
foldername = topic + '_' + 'Status_' + status
newFileName = foldername + '\\' + 'Message_' + '.xml'
if not os.path.exists(foldername):
os.mkdir(foldername)
shutil.copy(os.path.join(src, f), newFileName)
print('Sorting out files, please wait...')
classify()
print('¡DONE!')
最佳答案
您将所有内容命名为Message_
,因此您永远不会获得多个文件。您需要解析文件夹中的名称,然后相应地增加文件名。
msgName = 'Message_0'
newFileName = foldername + '\\' + msgName + '.xml'
if not os.path.exists(foldername):
os.mkdir(foldername)
else:
while os.path.isfile(newFileName) is True:
msgInt = int(msgName[8:])
msgInt += 1
msgName = msgName[:8] + str(msgInt)
newFileName = foldername + '\\' + msgName + '.xml'
shutil.copy(os.path.join(src, f), newFileName)
现在,如果您的文件夹中已有 message_0.xml
,您将获得 message_1.xml
,依此类推。
关于python - 如何将多个文件移动并重命名到特定文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56058177/