如何获取目录中的文件列表并在python中重命名

时间:2018-10-24 23:02:01

标签: python-3.x

我在使用for循环重命名文件时遇到问题。 起初,我在打开文件且无法重命名时遇到错误。 现在,我收到以下错误:TypeError:必须为整数(类型为str)

希望您能为我提供我的代码。

import fnmatch
import os


Path  = r'PATH'
file_name =""

for file in os.listdir(Path):
    if fnmatch.fnmatch(file, '*.txt'):
        with open(file, 'r') as f:
           fline = f.readline()[:1]
           lline = f.readlines()[-1]

           first = fline.replace("/", "#")
           last = lline.replace("/", "#")

        file_name = first + "_" +last + ".m12"

        os.rename(file, file_name)

这是我仅打印文件数据所得到的一个例子

    TypeError                                 Traceback (most recent call last)
<ipython-input-92-8f2ead3895f4> in <module>()
      8     if fnmatch.fnmatch(file, '*.txt'):
      9         print(file)
---> 10         with open(file, 'r') as f:
     11             fline = f.readline()[:1]
     12             print(fline) 

TypeError: an integer is required (got type str)

更新:

戴夫建议重命名我所做的文件,现在出现以下错误:

PermissionError                           Traceback (most recent call last)
<ipython-input-5-8727ecc0f786> in <module>()

 ---> os.rename(file_, file_name)
      (Above file was changed to file_)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process

1 个答案:

答案 0 :(得分:0)

我能够使它工作。 这是我对问题的解决方案。 Dave重命名了函数中循环的文件名,从而带我朝正确的方向前进。获得该帮助后,我发现仅使用open文件而不是with open文件将对我有帮助,因此我可以调用close函数。

感谢大家的帮助。

import fnmatch
import os


Path  = r'PATH'
file_name =""
nf = ""

for file in os.listdir(Path):
    if fnmatch.fnmatch(file, '*.txt'):
       f = open(file_, 'r')
       fline = f.readline()[:1]
       lline = f.readlines()[-1]

       first = fline.replace("/", "#")
       last = lline.replace("/", "#")

    fn = first + "_" +last + ".m12"

    f.close()
    os.rename(file_, fn)