Filename Containing Carriage Return On Windows Is Not Recognised By Python

- 1 answer

I would like to select a file, but the filename contains a carriage return and so .isfile() constantly returns False. While when I use .fnmatch() it prints the filename including the trailing carriage return.

import fnmatch
import os
local_path = 'd:'+os.sep
filename = '1F80813965EDAA4FC5BA44A91E0DBFF1'
local_file = os.path.join(local_path, filename+'\r')

print( os.path.isfile(local_file) ) 
# Returns False

for file in os.listdir(local_path):
    if fnmatch.fnmatch(file, filename+'?'):
        # Returns 'd:\\1F80813965EDAA4FC5BA44A91E0DBFF1\r'

What is the problem here? Is it Windows? Is it the NTFS partition? Or does the os.path.join() function not understand '\r'?



Windows doesn't allow special characters in filename:


  • Use a backslash (\) to separate the components of a path. The backslash divides the file name from the path to it, and one directory name from another directory name in a path. You cannot use a backslash in the name for the actual file or directory because it is a reserved character that separates the names into components.


  • Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:
    • The following reserved characters:
      • < (less than)
      • > greater than)
      • : (colon)
      • " (double quote)
      • / (forward slash)
      • \ (backslash)
      • | (vertical bar or pipe)
      • ? (question mark)
      • * (asterisk)
    • Integer value zero, sometimes referred to as the ASCII NUL character.
    • Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.
    • Any other character that the target file system does not allow.

If you copied the file from another system, this may be a problem. If you need to use this file in Windows, you would probably need to rename it before copying.