Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 发出重命名列表中的文件的命令_Python - Fatal编程技术网

Python 发出重命名列表中的文件的命令

Python 发出重命名列表中的文件的命令,python,Python,我试图从文本文件的列表中重命名一些mp3文件。 到目前为止,这是我的代码。在这里,在os.rename中,新名称有一个带有扩展名的新行。例如,这就是它试图重命名它的方式 01_pannam_38 .wav 出于某种原因,wav在下一行 import os lines=[] x=0 rootdir = r'C:\Users\kushal\Desktop\final_earthquake\redo_adaptation_mistakes_data\redo'

我试图从文本文件的列表中重命名一些mp3文件。 到目前为止,这是我的代码。在这里,在
os.rename
中,新名称有一个带有扩展名的新行。例如,这就是它试图重命名它的方式

01_pannam_38
.wav
出于某种原因,wav在下一行

   import os
    lines=[]
    x=0
    rootdir = r'C:\Users\kushal\Desktop\final_earthquake\redo_adaptation_mistakes_data\redo'

    with open('raw_result.txt', mode='r',encoding="utf-8") as f2:
      for line in f2:
          lines.append(line)


    x=0  
    for dirpath, dirnames, filenames in os.walk (rootdir):
     for file in filenames:
         filepath = dirpath +os.sep+file
         if filepath.endswith ('wav'):

          f_name, f_ext = os.path.splitext(file)

          os.rename(filepath, dirpath+os.sep+ lines[x]+f_ext)
          x=x+1

连接时可以去掉换行符。您需要将
行[x]
更改为
行[x].rstrip()

因此,它应该看起来像:

os.rename(filepath, dirpath+os.sep + lines[x].rstrip() + f_ext)
另外,@hiro progator在评论中指出,当附加

lines.append(line.strip())

lines.append(line.strip())
;文件行上的迭代包括尾随的
\n
。顺便说一下@hiroprotation thnx。