Python3重命名文件代码实现

版权声明:转载请注明出处,谢谢! https://blog.csdn.net/dreamstone_xiaoqw/article/details/90733537

说起来,小编实在时候菜的不行,许久不写Python,重命名个文件居然报了许多错……

为啥重命名呢?原因是想将文件名中的特殊字符去掉。

  • 报错(1)
$ python create_tbl_img.py
Traceback (most recent call last):
  File "create_tbl_img.py", line 13, in <module>
    out_file = out_file.replace("jpg", ".jpg")
AttributeError: 'filter' object has no attribute 'replace'
  • 报错(2)
$ python create_tbl_img.py
Traceback (most recent call last):
  File "create_tbl_img.py", line 14, in <module>
    out_file = path + out_file
TypeError: can only concatenate list (not "str") to list
  • 报错(3)
../imgs/<filter object at 0x00000179F7D7B2E8>
  • 报错(4)
Instance of 'filter' has no 'replace' member

这两个报错
查解决方案费了一些时间,主要原因是以最近写PHP的思维惯性,总觉着直接拼起来就好……

然而,在实际上Python3在处理这些问题会默认当做list来处理?这块待深究,暂时从输出信息看起来是这样的。

解决方法是字符串处理后,如需使用格式得这么写:

''.join(list(out_file))

完整代码如下:

#!C:/Python37
# coding:utf-8
import os
import shutil
path = "../imgs"
dir = "../imgs/"
for root, path, files in os.walk(path):
    for file in files:
        infile = dir + file
        out_file = filter(str.isalnum, file)
        out_file = str(''.join(list(out_file))).replace("jpg", ".jpg")
        out_file = dir + ''.join(list(out_file))
        # print(infile + "--" + out_file)
        if (infile != out_file):
            shutil.copyfile(infile, out_file)
            os.remove(infile)
            print(infile + "--" + out_file)

口说无凭,加个截图吧。

python-copyfile-remove-rename

经历过C、C++、C#、Python之后,才不得不承认:果然PHP才是世界上最好的语言。

猜你喜欢

转载自blog.csdn.net/dreamstone_xiaoqw/article/details/90733537
今日推荐