Raheem
Raheem

Reputation: 462

Text file does not get opened in output window.Python (Pycharm IDE)

So I just began learning Python and after making a file named myfile.txt I tried running this bit of code

def Main():
    f=open("myfile.txt","r")
    for line in f:
        print(line)
        f.close()

    if __name__ =="__main__":
        Main()

The file doesn't open , I'm just left with a blank output window.Any ideas what I did wrong? I'm using the Pycharm IDE on Windows.Please help.

Upvotes: 2

Views: 317

Answers (2)

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9756

First you need to make sure you indentions are correct. You should not close the file when inside the loop, so it's to much indented. And to run the program your if __name__ =="__main__": must be defined outside the function. Try this:

def main():
    f = open("myfile.txt","r")
    for line in f:
        print(line)
    f.close()

if __name__ =="__main__":
    main()

Usually you use the keyword with when handling files. It manages the opening and closing for you. Everything indented inside the with statement is done with the file being open. Try this, it's doing exactly the same:

def main():
    with open("myfile.txt", "r") as f:
        for line in f:
            print(line)

if __name__ == '__main__':
    main()

Upvotes: 3

Szabolcs Dombi
Szabolcs Dombi

Reputation: 5783

deindent the if

def Main():
    f=open("myfile.txt","r")
    for line in f:
        print(line)
        f.close()

if __name__ =="__main__":
    Main()

The if was part of your Main function, so you had a recursive function when the the condition was True

I believe you want the if to be tested after you define the function Main

Upvotes: 1

Related Questions