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

发布于 2025-01-15 10:22:25 字数 1087 浏览 1 评论 0原文

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

当我使用 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)}.")

As far as I know, I've done the indentation right, I also tried the same code in another text editor, but it throws the same error.

It throws "IndentationError: " when I use try except with "with open('file_name', 'mode') as file_handler:"

python3 test2.py
File "test2.py", line 9
except IOError:
^
IndentationError: expected an indented block

I learned similar articles, and it says indent consciously. I also tried with tab and 4 spaces, but it's not working either way.
Maybe it's a stupid mistake that I'm not getting.
Please help me, And I'd be grateful to get suggestions to do things better in this code so that I could learn something.

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)}.")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

妖妓 2025-01-22 10:22:25

您不能使用 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)}.")

You cannot interrupt the with statement with the except clause of the try statement. It has to be completed first. Some of the code can be moved out of the with statement and placed before or after (as appropriate) the try statement

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)}.")
泪眸﹌ 2025-01-22 10:22:25

您的代码完全错误,您不只是使用上下文管理器来打开文件,为此,我们有 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()

Your code is completely wrong, you don't use context manager just to open a file, for that, we have open(), we use with as a context manager so that it'll take care of closing the file later automatically.

and the syntax is wrong, you can't just leave the with statement hanging with a :, the operations on the file must be inside the with indentation.

anyway here is the right code

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文