【问题标题】:Python with open() as name - name not defined?以 open() 作为名称的 Python - 名称未定义?
【发布时间】:2019-11-29 18:33:59
【问题描述】:

我想打开一个包含一列单词的文本文件并创建一个列表,或者创建一个包含这些单词的字符串。为什么会出现此错误:

>>> with open(some_file.txt, 'r') as some_file:
...    some_list = [_ for _ in some_file.read().rstrip('\n')]
...    print(some_list)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'some_file' is not defined

【问题讨论】:

  • some_file.txt 作为标识符 -- ?
  • print(some_string) 也将失败,因为 some_string 未定义。
  • @RomanPerekhrest: some_file 是标识符,some_file.txt 是要打开的文件
  • @david,好吧,那是错误的尝试

标签: python file nameerror file-read


【解决方案1】:

Python 正在寻找一个名为 some_file 的对象而不是路径字符串

some_file.txt 替换为'some_file.txt'

【讨论】:

  • 快速跟进问题。让some_file.txt 包含五行文本: first second third Fourth Fifth 上面的代码给出:['f', 'i', 'r', 's', 't', '\n', 's', 'e'、'c'、'o'、'n'、'd'、'\n'、't'、'h'、'i'、'r'、'd'、'\n'、 'f', 'o', 'u', 'r', 't', 'h', '\n', 'f', 'i', 'f', 't', 'h'] 什么我需要: ['first', 'second', 'third', 'fourth', 'fifth'] 为什么read() 将单词拆分为符号,为什么rstrip('\n') 没有效果?
【解决方案2】:

所有问题都在这里得到解答:

When should I ever use file.read() or file.readlines()?

主题可以关闭。

【讨论】:

    猜你喜欢
    • 2019-11-13
    • 2020-09-03
    • 2023-02-07
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2021-10-18
    • 2016-05-16
    相关资源
    最近更新 更多