打开文件时出现NoneType错误

2024-10-01 17:30:38 发布

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

所以我一直在想它为什么会给我这个错误。如果我说:

def open_file():
    fp = open("ABC.txt")
    return fp

file = open_file()

count = 1

for line in file:
    if count == 9:
        line9 = line
    if count == 43:
        line43 = line
#blahblahblah more programming

这是可行的,但这给了我非类型对象是不可编辑的:

^{pr2}$

我觉得这是愚蠢的,但我找不到。 谢谢你的时间!在


Tags: intxtforreturnifdefcount错误
1条回答
网友
1楼 · 发布于 2024-10-01 17:30:38

您的open_file函数没有return语句,因此它返回None。你应该试试

def open_file():
    while True:
        file = input("Enter a file name: ")
        try:
            return open(file)
        except FileNotFoundError:
            print("Error. Please try again.")
            print()

相关问题 更多 >

    热门问题