我想把所有的.csv檔案重命名為假設mac&cheese_12012010, mac&cheese_13012010, mac&cheese_14012010, mac&cheese_15012010, mac&cheese_16012010.......,只保留'_'后面的部分。 我想從根本上洗掉mac&cheese,并保留python中的日期。
uj5u.com熱心網友回復:
你可以使用os.rename。
import glob, os
for old in glob.glob('mac& cheese_*.csv'):
new = old[len('mac&cheese_') :]
os.rename(old, new)
注意,在linux上,如果目標檔案存在,它似乎會覆寫它們。在Windows上,它似乎不會覆寫檔案。總之,在處理檔案的時候,要小心謹慎。
另外,在Python 3.9以上版本中,你可以替換
用 這對可讀性來說是更好的。只要不要使用 uj5u.com熱心網友回復: 請閱讀如何提出一個好的問題并提供一個可重復的資料集。要回答你的問題,有多種方法,包括:
uj5u.com熱心網友回復: 你可以在檔案所在的目錄中運行這段代碼 uj5u.com熱心網友回復:
標籤:new = old >。
new = old[len('mac&cheese_'):]/code>new = old.removeprefix('mac&cheese_')old.lstrip()就行了。
import glob
import os
files = glob.glob('/path/to/files/*.csv')
for file in files:
new_name = file.replace('mac& cheese_','')
os.rename(file,new_name)
import os
# ONELINER>
[os.rename(f, f.replace("mac&cheese_", "") for f in os.listdir() if f.endswith(".csv") ]
OR
for file in os.listdir() 。
if file.endswith(".csv")。
os.rename(file, file.replace("mac&cheese_", " ")
import os
# 更改目錄
folder = r'E:demosfiles
eports/'
# For Windows folder = r'E:/demos/files/reports/'
for file_name in os.listdir(folder):
if file_name.endwith(".csv")。
source = folder file_name
# We only want the dates: source = folder file_name.
destination = file_name.split('_')[1] " .csv"
# 重命名檔案。
os.rename(source, destination)
