python批量修改文件程序代码

来源:互联网 发布:js a href 赋值 编辑:程序博客网 时间:2024/05/17 23:46

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

原创粉丝点击