python要求用户输入文件名

2024-05-03 20:15:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在学习python课程,这段代码不适用于VSCode或我的命令提示符。我真的不知道是什么问题,有人能帮我吗

fname = input()
fhand = open(fname)
count = 0
for line in fhand:
    if line.startswith('Subject:'):
        count = count + 1
print('There were', count, 'subject lines in', fname)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fhand' is not defined
>>> print('There were', count, 'subject lines in', fname)
There were 0 subject lines in fhand = open(fname)

目前正在使用Python 3.9

enter image description here


Tags: 代码incountlineopenvscodefname课程
1条回答
网友
1楼 · 发布于 2024-05-03 20:15:04

您正在Python解释器中运行代码吗

似乎第一行被执行,第二行作为第一行的输入。因此,fname被设置为fhand = open(fname)

这导致没有定义为fhand的变量,因此没有定义错误名称fhand

计数设置为0,因此print语句给出输出

There were 0 subject lines in fhand = open(fname)

[解决方案] 尝试将代码保存到.py文件中,然后使用以下命令运行代码:

python3 <fileName.py>

相关问题 更多 >