Search code examples
pythonindentation

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()

Solution

  • You are mixing tabs and spaces. Don't do that. Specifically, the __init__ function body is indented with tabs while your on_data method is not.

    Here is a screenshot of your code in my text editor; I set the tab stop to 8 spaces (which is what Python uses) and selected the text, which causes the editor to display tabs with continuous horizontal lines:

    highlighted code with tabs shown as lines

    You have your editor set to expanding tabs to every fourth column instead, so the methods appear to line up.

    Run your code with:

    python -tt scriptname.py
    

    and fix all errors that finds. Then configure your editor to use spaces only for indentation; a good editor will insert 4 spaces every time you use the TAB key.