gpt4 book ai didi

python - Python 无法识别 Windows 上包含回车符的文件名

转载 作者:可可西里 更新时间:2023-11-01 11:42:45 27 4
gpt4 key购买 nike

我想选择一个文件,但文件名包含一个回车符,因此.isfile() 不断返回False。当我使用 .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'

这里有什么问题?是 Windows 吗?是NTFS分区吗?或者 os.path.join() 函数不理解 '\r'

最佳答案

Windows 不允许 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.

如果您从另一个系统复制文件,这可能是个问题。如果您需要在 Windows 中使用此文件,您可能需要在复制前重命名它。

关于python - Python 无法识别 Windows 上包含回车符的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54589375/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com