簡體   English   中英

更改多個文件名 python

[英]CHange multiple file name python

我在手動更改文件名時遇到問題 我有很多文件名的文件夾

202012_34324_3643.txt
202012_89543_0292.txt
202012_01920_1922.txt
202012_23442_0928.txt
202012_21346_0202.txt

我希望將其重命名如下刪除_之前和之后的數字,在下划線之間留下數字。

34324.txt
89543.txt
01920.txt
23442.txt
21346.txt

我想要一個讀取文件夾中所有文件的腳本,像上面提到的那樣重命名它。 謝謝

您可以嘗試使用 python 中的os庫。

import os

# retrieve current files in the directory
fnames = os.listdir()
# split the string by '_' and access the middle index
new_names = [fnames.split('_')[1]+'.txt' for fname in fnames]

for oldname, newname in zip(fnames, new_names):
    os.rename(oldname, newname)

這將為當前目錄完成工作。

import os

fnames = os.listdir()
for oldName in fnames:
    if oldName[-4:] == '.txt' and len(oldName) - len(oldName.replace("_","")) == 2:
        s = oldName.split('_')
        os.rename(oldName, s[1]+'_'+s[2]+'.txt')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM