python批量修改文件程序代碼

1:首先我們來介紹幾個函數
os.listdir(path);會得到這個給定的目錄中的所有東西——文件和目錄
os是python內置的模塊叫做os操作系統(operating system)的簡稱。
rename(src,dst):給文件或文件夾改名(可以改路徑,但是不能覆蓋目標文件)
string.translate()requires a dict that maps unicode ordinals to other unicode oridinals (or None if you want to remove the character).
例如:

old_string = "file52.txt"
to_remove = "0123456789"
table = {ord(char): None for char in to_remove}
new_string = old_string.translate(table)
assert new_string == "file.txt"

However, there is simpler way of making a table though, by using the str.maketrans function. It can take a variety of arguments, but you want the three arg form. We ignore the first two args as they are for mapping characters to other characters. The third arg is characters you wish to remove.

old_string = "file52.txt"
to_remove = "0123456789"
table = str.maketrans("", "", to_remove)
new_string = old_string.translate(table)
assert new_string == "file.txt"

2:因此到了這裏,我們可以寫個給批量文件的文件名去掉數字的程序
os_1.png
當我們運行程序時確發現控制檯出現了這樣的結果。
0s_2.png
問題是出在了第九行,用os.getcwd()函數得到當前工作目錄。

參考鏈接:
python官方API os模塊
translate() takes exactly one argument (2 given) in python error

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章