[英]Filename containing carriage return on Windows is not recognised by Python
I would like to select a file, but the filename contains a carriage return and so .isfile()
constantly returns False
.我想选择一个文件,但文件名包含回车符,因此
.isfile()
不断返回False
。 While when I use .fnmatch()
it prints the filename including the trailing carriage return .当我使用
.fnmatch()
它会打印文件名,包括尾随回车。
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+'?'):
print(repr(file))
# Returns 'd:\\1F80813965EDAA4FC5BA44A91E0DBFF1\r'
What is the problem here?这里有什么问题? Is it Windows?
是 Windows 吗? Is it the NTFS partition?
是NTFS分区吗? Or does the
os.path.join()
function not understand '\\r'
?还是
os.path.join()
函数不理解'\\r'
?
Windows doesn't allow special characters in filename : Windows 不允许在 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:
使用当前代码页中的任何字符作为名称,包括 Unicode 字符和扩展字符集 (128–255) 中的字符,但以下字符除外:
- 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.
整数值零,有时称为 ASCII NUL 字符。
- Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed.
整数表示在 1 到 31 范围内的字符,但允许这些字符的备用数据流除外。 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.
如果您需要在 Windows 中使用此文件,则可能需要在复制之前重命名它。
In your code, the following line is creating a path to file.在您的代码中,以下行正在创建文件路径。 You can try to remove
\\r
in it.您可以尝试删除其中的
\\r
。
local_file = os.path.join(local_path, filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.