I’m trying to run the following code in python3, but it has been written for I’m pretty sure python2:
f = open(filename, 'r')
self.lines = f.readlines()
f.close()
if self.lines[-1] != "\n" :
self.lines.append("\n")
But I’m getting the following error:
File "randline.py", line 32
if self.lines[-1] != "\n" :
^
TabError: inconsistent use of tabs and spaces in indentation
Can you help me figure out the correct syntax?
Python 2 allows you to mix spaces and tabs. so you can have indentation like:
Line 2 and line 4 will in Python 2 have the same indentation level, but line 2 will do it with a tab, and line 4 will do it with spaces. Printed to the console, it will look like this:
But most editors allow you to set how many spaces a tab should be. Set it to four, and you get this:
The indentation is still the same, but now it looks like the indentation is wrong!
Python 3 therefore do not allow the same indentation level (ie line 2 and 4) to be indented in different ways. You can still mix tabs and spaces, but not in the same indentation level. This means that
will work, and so will
The only way to make that the only way you can make the indentation look weird is of you set a tab to be more than eight spaces, and then the indentation not only looks obviously incorrect, you’ll notice that a tab will indent 12 spaces (in the below example) so you realize you insert a tab, and not four spaces.
Of course, the solution to all your problems is as written in the comments, to never use tabs. I’m not sure why Python 3 still allows tabs at all, there is no good reason for that, really.