gpt4 book ai didi

python - os.path.exists 使用整数

转载 作者:行者123 更新时间:2023-12-05 03:16:47 27 4
gpt4 key购买 nike

今天,我正在编写一段代码,在对文件执行任何操作之前检查文件是否存在。为此,我使用

os.path.exists( filename )

错误地,我给文件名一个整数值而不是一个字符串值。例如

os.path.exists( 15 )

令我非常惊讶的是,它没有引发 TypeError 但返回了 True(它实际上为我尝试的任何整数返回了 True)。

为什么会起作用,这个结果有什么意义?

最佳答案

来自documentation

Changed in version 3.3: path can now be an integer: True is returned if it is an open file descriptor, False otherwise.

当我尝试它时,它只为几个小数字返回 True:

>>> [os.path.exists(n) for n in range(50)]
[True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]

关于python - os.path.exists 使用整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74493341/

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