[python] Python IndentationError unindent does not match any outer indentation level

I'm a beginner in python,

I have this error :

Error : 
def on_data(self,data):
                      ^
IdentationError : unindent does not match any outer indentation level

I code with notepad++ in windows 8.1. I don't understand why I have this error, I have paid attention about tabs and space.

I want to save data in self.file

Here is my code :

from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from tweepy import Stream
import tweepy
import time



class StdOutListener(StreamListener):

    def __init__(self,file):
        self.file = file

    def on_data(self, data):

        print data
        self.file.write(data)
        return True

    def on_error(self, status):
        print status


def main() :
    file = open('work.txt','w')
    listn = StdOutListener(file)
    consumer_key=""
    consumer_secret=""

    access_token=""
    access_token_secret=""

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    #api = tweepy.API(auth)

    #filename=open('helloworld.txt','r')
    #f=filename.readlines()
    #filename.close()

    #for line in f:
    #   api.update_status(line)

    stream = Stream(auth, listn)
    stream.filter(track=['lol'])
    file.close()

This question is related to python indentation

The answer is


I recently ran into the same problem but the issue wasn't related to tabs and spaces but an odd Unicode character that appeared invisible to the eye in my IDE. Eventually, I isolated the problem and typed out the line exactly as it was and checked the git diff:

enter image description here

If you are able to isolate the line before the reported line and type it out again, you might find that it solves your problem. Won't tell you why it happened in the first place, but it at least gets rid of the issue.



You have mixed indentation formatting (spaces and tabs)

On Notepad++

Change Tab Settings to 4 spaces

Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

Fix the current file mixed indentations

Select everything CTRL+A

Click TAB once, to add an indentation everywhere

Run SHIFT + TAB to remove the extra indentation, it will replace all TAB characters to 4 spaces.


make sure """ comments are only a tab away and not 5 spaces


i have done proper indentation with spaces but syoll it was throwing error. Then I removed al the spaces and use Tab then it started working. thx


I had the same problem quite a few times. It happened especially when i tried to paste a few lines of code from an editor online, the spaces are not registered properly as 'tabs' or 'spaces'.

However the fix was quite simple. I just had to remove the spacing across all the lines of code in that specific set and space it again with the tabs correctly. This fixed my problem.