You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何‘if data is None’语句无法正常执行?

问题:判断空文件时逻辑错误导致提示不显示

尝试编写代码实现:读取用户指定的文件,若文件为空则输出“该文件无数据”。但读取empty.txt空文件时,程序直接跳过if分支执行else,终端仅显示输入提示,未出现预期的空文件提示信息。

原代码如下:

# Ask user to input file, open and and read file

userinput = input('Enter name of file: ')

userfile = open(userinput)

data = userfile.read()

#if file is empty print "x contains no data"

if data is None:
    print(userinput + ' contains no data.')
else:
    print(data)

userfile.close()

错误原因

当使用file.read()读取空文件时,返回的是空字符串'',而非None。原代码用if data is None:判断,无法匹配空文件的情况,因此会执行else分支打印空字符串(终端无可见输出)。

修正方案

将判断条件改为检查字符串是否为空,有两种等价写法:

  • 利用空字符串在布尔判断中为False的特性,直接写if not data:
  • 明确判断data == ''

同时推荐使用with语句打开文件,它会自动帮你关闭文件,避免资源泄漏。修正后的代码如下:

# 询问用户输入文件名,打开并读取文件
userinput = input('Enter name of file: ')

with open(userinput) as userfile:
    data = userfile.read()

# 如果文件为空,输出提示
if not data:
    print(f'{userinput} contains no data.')
else:
    print(data)

内容的提问来源于stack exchange,提问作者Filth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 04:05:26