Beginner file in python

Hey,guys!Trying to create a txt file in Python,but something goes wrong!Please,explain what and why

You haven’t defined the Main function.Put everything that you have typed inside the main function
It should be
def main():
your code comes here
closing below
if_ _ name_ _ == “_ _ main_ _”
main()

1 Like

I mean there’s nothing wrong with the code since it works in repl.it

But maybe it is in the way you’re calling it? Also tested it on my machine (Ubuntu) as python main.py and it yielded the txt.

1 Like
f=open("guru.txt","w+")
for i in range(10):
	f.write("This is line% d\t\n"%(i+1))

f.close()

Hope this helps.

1 Like

The code works just fine for me

As an side from your question. Instead of just calling open, you can use a command with, and when you leave that block of code, the file is closed. As it is now, if you have an error somewhere between your open and close command, you can be kicked out from your program while you file remains open in memory with no way to close that instance. So toss out your close command, and use with.

with open("guru.txt", "r") as f:
    lines = f.readlines()

print(lines)