The only problem is it throws "IndentationError: " when I use try except with "with open('file_name', 'mode') as file_handler:"

The only problem is it throws "IndentationError: " when I use try except with "with open('file_name', 'mode') as file_handler:"

据我所知,我已经正确地缩进了,我也在另一个文本编辑器中尝试了相同的代码,但它抛出了同样的错误。

当我使用 try except with "with open('file_name', 'mode') as file_handler:"

时抛出 "IndentationError: "

python3 test2.py 文件“test2.py”,第 9 行 除了 IOError: ^ IndentationError:需要一个缩进块

学过类似的文章,上面写着自觉缩进。我也试过使用 tab 和 4 个空格,但不管怎样都行不通。 也许这是一个愚蠢的错误,我没有得到。 请帮助我,我将不胜感激获得建议以在此代码中做得更好,以便我可以学到一些东西。

f_name = input("enter a file name:: ")

if f_name == 'na na boo boo':
    print(f"\n{f_name} TO YOU - You have been punk'd!\n")
    exit()
try:
    with open(f_name, 'r') as f_hand:

except IOError:
    print(f'File missing:: {f_name}.')
    exit()

    floating_points = []

    for line in f_hand:

        if line.startswith('X-DSPAM') :
            start_index_pos = line.find(':')
            start_index_pos = float(start_index_pos)
            floating_points.append(start_index_pos)
    print("The floating points are::\n")

    for floating_point in floating_points:
        print(floating_point)
    print(f"There are {len(floating_points)} items on the list and they sum to {sum(floating_points)}.")

不能用 try 语句的 except 子句中断 with 语句。它必须先完成。一些代码可以移出 with 语句并放置在 try 语句

之前或之后(视情况而定)
floating_points = []

try:
    with open(f_name, 'r') as f_hand:
        for line in f_hand:
            if line.startswith('X-DSPAM') :
                start_index_pos = line.find(':')
                start_index_pos = float(start_index_pos)
                floating_points.append(start_index_pos)
except FileNotFoundError:
    print(f'File missing:: {f_name}.')
    exit()

print("The floating points are::\n")
for floating_point in floating_points:
    print(floating_point)
print(f"There are {len(floating_points)} items on the list and they sum to {sum(floating_points)}.")

你的代码是完全错误的,你不使用上下文管理器只是为了打开一个文件,为此,我们有 open(),我们使用 with 作为上下文管理器,所以它会注意稍后自动关闭文件。

而且语法不对,不能让with语句挂着:,对文件的操作必须在with缩进里面。

无论如何这是正确的代码

f_name = input("enter a file name:: ")

if f_name == 'na na boo boo':
    print(f"\n{f_name} TO YOU - You have been punk'd!\n")
    exit()
try:
    with open(f_name, 'r') as f_hand:
        floating_points = []

        for line in f_hand:

            if line.startswith('X-DSPAM'):
                start_index_pos = line.find(':')
                start_index_pos = float(start_index_pos)
                floating_points.append(start_index_pos)
        print("The floating points are::\n")

        for floating_point in floating_points:
            print(floating_point)
        print(f"There are {len(floating_points)} items on the list and they sum to {sum(floating_points)}.")
except IOError:
    print(f'File missing:: {f_name}.')
    exit()