0

When I compile the Python code below, I get IndentationError: unindent does not match any outer indentation level

with open('test.txt','r') as f:
    import sys
    f_contents= f.read(100)
    print(f_contents,end='')
    f_contents= f.read(100)
    print(f_contents,end='')

Can any body explain why that happens?

MattDMo
  • 100,794
  • 21
  • 241
  • 231

3 Answers3

0

Working for me!

Can you show the exact line where the error occurred and the input file

Possible reason: If this part of some file, then you might be using mix of tabs and spaces

enter image description here

Code I used:

with open('test.txt','r') as f:
    import sys 
    f_contents= f.read(100)
    print(f_contents,end='')
    f_contents= f.read(100)
    print(f_contents,end='')
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
0

Indentation of your code matters in Python, the code won't run if the indentation is not correct. The code you posted, should be indented as follows. The with statement needs an indent (like an if statement or for loop would).

import sys

with open('test.txt','r') as f:
    f_contents = f.read(100)
    print(f_contents,end='')
    f_contents= f.read(100)
    print(f_contents,end='')

Note: import sys isn't needed for that bit of code to run, but usually you should have import statements at the top of your code.

Dominic D
  • 1,778
  • 2
  • 5
  • 12
0

try this:

     with open('test.txt','r') as f:
         import sys
         f_contents= f.read(100)
         print(f_contents,end='')
         f_contents= f.read(100)
         print(f_contents,end='')  

with require proper indentation

Om Khade
  • 40
  • 6