'Python: Rename multiple files in folder with name that come from a list

I want to build a small app that renameS files that are in a folder with some names that are in a txt file like so:

in C:\python\Folder i have files: 1436790.pdf 1436791.pdf 1436792.pdf

in file.txt I have 3 lines:

  1. x
  2. y
  3. z

Renaming should be:

  1. 1436790.pdf -> x.pdf
  2. 1436791.pdf -> y.pdf
  3. 1436792.pdf -> z.pdf

I can't figure out how os.rename() is working. I'm getting this error

**"OSError: [WinError 87] The parameter is incorrect:"**

I tried to make this app in a similar way with Total Commander multi rename tool (load names from file).



Solution 1:[1]

basefolder=r'C:\python\Folder'
with open('file.txt', 'r') as fh:
    read_lines = fh.readlines()
files=os.listdir(basefolder)
for file in r(files):
    fn,fext=os.path.splitext(files[file])
    os.rename(files[file], read_lines[file]+fext )

Solution 2:[2]

Looks like this is due to the pytest/Python bug issue. Refer https://github.com/pytest-dev/pytest/issues/5724

For now try downgrading to Python 3.7.3 until someone finds a fix.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Farhang Amaji
Solution 2 Aniesh Das