开发者

Removing carriage return characters from a file using python

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?


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).


You can use str.rstrip('\r') method to remove a set of characters from the right side of a string:

>>> s="this is your brain on drugs\r\n\r\n"
>>> s
'this is your brain on drugs\r\n\r\n'
>>> s=s.rstrip('\n\r ')
>>> s
'this is your brain on drugs'

You say in your post that the file name has a \r at the end of it; this would be very unusual. Are you sure that your file name has a \r at the end of the string or you are assuming it does because you used Python to print it? Remember that Python appends an automatic return to a string that you print.

Edit

OK: the file name really has a \r on the end. My first recommendation is to fix the script that is producing such unfriendly file names...

For this scipt, you need to either prepend the directory name on the front or CD into the relevant directory. Since THIS answer has the prepending, here is CD'ing:

try:
    os.chdir(sys.argv[1])
except OSError:
    print "can't change to ",sys.argv[1]
    sys.exit(1)

# proceed with the rest of your script... 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜