Vamos Kostas
Vamos Kostas

Reputation: 3

Indentation Error in python 3.6

When i run this code in IDLE, i get a SyntaError(expected an indent block) The thing is that i dont see any indentation problem. What the code does: It reads 'cities.txt' file(with string lines) It then copies those lines in 'out.txt', after enumeration in each line

try:
    with open('cities.txt', 'r+') as inp:
except FileNotFoundError:
    print('File not found')
except:
    print('Error')
else:
    try:
        with open('out.txt', 'a+') as out:
    except FileNotFoundError:
        print('File not found')
    except:
        print('Error')
    else:
        for i, line in enumerate(inp):
            out.write(str(i+1)+': '+line)
            print(str(i+1)+': '+line, end='\n')

Upvotes: 0

Views: 122

Answers (2)

Vyko
Vyko

Reputation: 212

To ensure logic and format, you should write your code like this :

try:
    with open('out.txt', 'a+') as out:
        for i, line in enumerate(inp):
            out.write(str(i+1)+': '+line)
            print(str(i+1)+': '+line, end='\n')
except FileNotFoundError:
    print('File not found')
except:
    print('Error')

Upvotes: 2

Ophir Yoktan
Ophir Yoktan

Reputation: 8449

with x as y: should be followed by an indented code block that does what you want with the resource - basically what you now have in the else block

Upvotes: 2

Related Questions