Guide: Write \ Read txt - Toby-eaaa/Mini_Pupper_eaaa GitHub Wiki
how to read and write from txt files in python.
in this tutorial we're going to learn how to write a single line to a file and read it again in a way that is repeatable indefinitely.
this webpage.
You can aprach read and write in different ways if you want. for more in-depth info, seeWriting
To write to a file, we need to create the file and set the access mode. this is done by the template:
file = open(filename, access_mode)
open() obviously opens a file, but it also creates a file if there isn't one by that name already present. If no file path is added, the file will be created in the same folder as the code.
to open/create a file with write access mode, write:
file1 = open("Text.txt", "w")
to open/create a file in another folder:
file1 = open("/folder1/folder2/folder3/Text.txt", "w")
you can also use "w+" if you want to be able to both read and write to the file in the same program.
now, let's write to the file.:
file1.write("Witness me!")
We can only write strings to txt files, so if we want to write other types to the file, we have to cast them to string and then cast them back after reading:
file1.write(str(22))
When we're done with the file, we close the file so it can be accessed from elsewhere:
file1.close()
full example Write function
def writetext(Out):
file1 = open("Text.txt", "w")
file1.write(Out)
file1.close()
Reading
Reading from a file follows the same basic procedure. We open a file, read from it and close it.
This time we open the file with "r" access mode instead of "w":
file1.open("Text.txt", "r")
When we read from the file, we can either print it to console or save it to a variable:
print(file2.read())
StringTemp =file2.read()
finally, we of course close the file again:
file1.close
full example Read function
def readtext():
file2 = open("Text.txt", "r")
StringTemp =file2.read()
file2.close()
return StringTemp