我正在嘗試使用 Python 重命名一組 .txt 檔案。我可以成功地將檔案重命名為所需的新命名約定,但如果腳本運行不止一次,或者目錄中的某些檔案已經使用正確的命名約定,則檔案名開始變得多余。到目前為止,這是我的這個程序的代碼。
os.chdir('C:\Users\Phillip\Circuit_generation\Automation\Test_files\\')
sc_files = glob.glob('*sc.txt')
print('All netlist files ending with a series capacitor:')
for file_name in sc_files:
order = int(file_name.count('sc') file_name.count('sl') file_name.count('pc') file_name.count('pl'))
old_name = file_name
new_name = 'Order_{}_{}'.format(order, old_name)
if os.path.isfile(new_name):
pass
else:
os.rename(old_name, new_name)
print(new_name)
該腳本正在搜索目錄并查找以特定文本結尾的所有檔案。然后我嘗試遍歷所有符合該條件的檔案。計算電路的階數。我記錄當前檔案名,然后定義一個新名稱。
我想要的是最終得到格式如下的檔案:
Order_5_sc_pl_sl_pc_sc
但是,如果此腳本運行不止一次或檔案已經符合此命名約定,我開始獲取檔案名,例如:
Order_5_Order_5_sc_pl_sl_pc_sc
Order_5_Order_5_Order_5_sc_pl_sl_pc_sc
I have tried to check if the old name matches the new naming convention and pass if the name is already in the correct format, but I can't solve the problem. This code is my latest attempt to try to stop the files from being named incorrectly. I think this attempt is failing because I am not really allowing the old name to ever match the new name, but I can't seem to find a solution. I also tried the following but got similar results:
print('All netlist files ending with a series capacitor:')
for file_name in sc_files:
order = int(file_name.count('sc') file_name.count('sl') file_name.count('pc') file_name.count('pl'))
old_name = file_name
if os.path.isfile('Order_{}_{}'.format(order, old_name[8:])):
pass
else:
new_name = 'Order_{}_{}'.format(order, old_name)
os.rename(old_name, new_name)
print(new_name)\
How can I go about renaming only the files that are necessary to rename and not continue creating long redundant file names? I am not sure what I am doing wrong and would greatly appreciate any help on the matter. Thank you.
uj5u.com熱心網友回復:
您能否提供一些您開始使用的示例檔案名,以便我們為您提供幫助?另外,請不要使用格式功能,現在大多數人都使用 f-strings,而“”僅用于將多行合并為一行。
根據我從您的問題中得到的資訊,這就是我想出的。我的代碼的一個副作用可能是訂單的順序可以改變,即:“sc_pl_sl_pl_sc”到“Order_sc_pl_pl_sl_sc”
import os
def get_all_orders(file_name):
all_orders = []
orders_amount = 0
order_types = {"pl", "sl", "pc", "sc"}
for order_type in order_types:
order_type_amount = file_name.count(order_type)
all_orders = [order_type] * order_type_amount
return orders_amount, all_orders
for file_name in ["Order_5_sc_pl_sl_pc_sc", "sc_pl_sl_pc_sc"]:
if "Order_" not in file_name:
orders_amount, all_orders = get_all_orders(file_name)
new_filename = "Order_" "_".join(all_orders)
if not os.path.isfile(new_filename):
# os.rename(file_name, new_name)
print(f"os.rename({file_name}, {new_filename})")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427734.html
