-2

I am trying to rename some mp3 files from a list in a text file. So far this is my code. Here, at os.rename the new name has a new line attached with extension. For example, this is how it is trying to rename it

01_pannam_38
.wav

For some reason .wav is on the next line

   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
choman
  • 787
  • 1
  • 5
  • 24

1 Answers1

1

You could strip out the newline when concatenating. You need to change lines[x] to lines[x].rstrip()

So, it should look like :

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

Also, @hiro protagonist pointed in comment, you can strip out newline when appending by

lines.append(line.strip())
Ravi
  • 30,829
  • 42
  • 119
  • 173