[英]Python move file to folder based on both partial of file name and value of another partial of file name
文件夾中有3個文件:
my_floder:
Review Report - 2020-3.20230110151743889.xlsx
Review Report - 2020-3.20230110151753535.xlsx
Review Report - 2019-4.20230110151744423.xlsx
每個文件名有3個部分,以第一個文件為例:
First Part:"Review Report -"
Second Part:"2020-3"
Third Part:".20230110151743889"
邏輯是:如果有些文件的第二部分文件名相同,則只選擇第三部分值較大的文件移動到另一個文件夾。文件名的第三部分是時間戳,yyyymmddhhmm ...
例如,前兩個文件的第二部分相同,但由於第二個文件 Review Report - 2020-3.20230110151753535.xlsx 的文件名“20230110151753535”的第三部分很大,因此只會復制第二個和第三個文件到另一個文件,第一個文件將被跳過。
一些有用的腳本:
parts_list=os.path.basename(filename).split(".")
output is:
['Review Report - 2020-3', '20230110151743889', 'xlsx']
second_part = parts_list[0].split(" - ")[1]
output is:
'2020-3'
thrid_part=parts_list[1]
output is:
20230110151743889
我能做的最好的:
unique = []
for filename in glob.glob(my_floder):
parts_list=os.path.basename(filename).split(".")
second_part = parts_list[0].split(" - ")[1]
thrid_part=parts_list[1]
if second_part not in unique:
unique.append(second_part)
else:
# here need to compare the value of the third part ,and move the file with larger third part to another folder but I have no idea how to do that
有朋友可以幫忙嗎?
我會用字典:
unique = {}
for filename in glob.glob(my_floder):
parts_list=os.path.basename(filename).split(".")
second_part = parts_list[0].split(" - ")[1]
thrid_part=parts_list[1]
if second_part not in unique or float(unique.get(second_part)) < float(third_part):
unique.update({second_part: third_part})
由於third_part
包含一個點,因此最容易將其視為浮點數。 它切斷了最后一位數字,但我希望我們可以假設不同的版本不會相隔幾秒保存。
合並 if
和elif
可能有更好的方法,但如果不滿足第一個條件,可能會出現一些並發症;我會把它留給你。 -- 仔細觀察后,我意識到如果不滿足第一個條件,它保證second_part
是字典中的有效鍵,因此它們可以合並。
不是最簡潔或最好的解決方案,但它應該有效。
您可以使用collections.defaultdict
創建dict
,並在每次迭代中為每個第二部分保留最大datetime
時間。
from datetime import datetime
from collections import defaultdict
import shutil
res = defaultdict(lambda:0)
for file in glob.glob(my_floder):
fs, t = file.split('.', 1)
f, s = fs.split(' - ')
tmp = datetime.strptime(t, '%Y%m%d%H%M%S%f.xlsx')
if (not res[s]) or tmp > datetime.strptime(res[s], '%Y%m%d%H%M%S%f.xlsx'):
res[s] = t
# You can find max datetime in filename like below and move to folder
for k,v in res.items():
print(f"Review Report - {k}.{v}")
file_name = f"Review Report - {k}.{v}"
shutil.move(file_name,
f'new_path/{file_name}')
Output:
Review Report - 2020-3.20230110151753535.xlsx
Review Report - 2019-4.20230110151744423.xlsx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.