Search code examples
pythonpython-3.xfile-ioindentation

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


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

Solution

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