How to: Files for Python
A lot of people (like two people lol) have asked me how to make the program automatically create a file and store stuff to it. Well do I have an answer for you! Today I'll be teaching you just that!
1st things 1st, create a repl in python. Make sure it is python 3 and not python 2.
Now once that is done it should look like this.
Now, I'll explain how the open() works. How it works is opening a file for a certain operation. The operation are as follows:
w+: write something and if the file doesnt exist then create a new file
now that this is explained, lets code!
Of course you can always edit this code and make it do amazing things.
first we need to actually declare a variable to do the open() command for us.
so lets assign f to do that.
f = open('file.txt', 'w+')
this code wont actually work until we tell it to do so. The way we do that is we use write(). The syntax for write() is :
f = open('file.txt', 'w+') f.write('Hello world!') f.close()
In this case I'm also telling it to make a new file and telling it to write Hello World to it.
and it'll create a new file when I run it and add hello world to its contents.
Make sure to put f.close() which closes the operation otherwise it won't write to the file.
As you can see it created a new file and in it says hello world! Now, what do we do to add more sentences to the file? We replace the w+ with a. Otherwise the sentence gets overwritten.
f = open('file.txt', 'a') f.write('Hello world!') f.close()
If we wanted it in a new line we would use the escape key for that. so we would put \n right before hello world. Now what if we ever wanted to print what the file said? we would use .read() and assign to variable.
Make sure to re-open the file but this time as a read operation. Also re-close the 2nd operation after printing the contents. X3
Your code should look like this when it's finished:
f = open('file.txt', 'a') f.write('\nHello world!') f.close() f = open('file.txt', 'r') contents = f.read() print(contents) f.close()
This is the basics of the file handling. I hope this helped someone if there is anything that needs to be added Comment below your question and I will collect them all and make a part 2 with all your questions answered.
Here is the Example Repl if you need to fork it.
Have a good day everyone!