Removing carriage return characters from a file using python

LearnCode picture LearnCode · Apr 2, 2011 · Viewed 7.4k times · Source
import os
import sys

files = os.listdir(sys.argv[1])
for file in files:
    if file[-4:] == ".png":
        os.rename(file, file.replace('\r', ''))

Am using the above code to remove \r from the file name, but some how when I execute I get the following error

Traceback (most recent call last):
  File "renameImages.py", line 9, in <module>
    os.rename(f, f.replace('\r', ''))
OSError: [Errno 2] No such file or directory

Where am I going wrong?

Answer

Property404 picture Property404 · Apr 2, 2011

You didn't tell it the directory of the file, that was declared in argv[1] try os.rename(sys.argv[1]+"/file",sys.argv[1]+"/"+replace('\r'','') (or '\\' for Windows).