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...
file
" as a variable name. There is a builtin by the same name. consider "filename"? Unrelated to the issue you're having.