唯一的问题是,当我使用 try except 和“with open('file_name', 'mode') as file_handler:”时,它会抛出“IndentationError:”[重复]

问题描述 投票:0回答:2

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

当我使用 try except 和“with open('file_name', 'mode') as file_handler:”时,它会抛出“IndentationError:”

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

我学过类似的文章,上面说有意识缩进。我也尝试过使用制表符和 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)}.")
python python-3.x file-io indentation
2个回答
0
投票

您不能使用

with
语句的
except
子句打断
try
语句。它必须首先完成。某些代码可以移出
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)}.")

0
投票

您的代码完全错误,您不只是使用上下文管理器来打开文件,为此,我们有 open(),我们使用

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()
© www.soinside.com 2019 - 2024. All rights reserved.