with open(filename, "r+") as f:
data = f.read()
f.seek(0)
f.write(output)
f.truncate()
'''
You can read and write in files with open()
'r' = read
'w' = write (overwrite)
'a' = append (add)
NOTE: You can use shortened 'file.txt' if the file is in the same
directory (folder) as the code. Otherwise use full file adress.
'''
myFile = open('file.txt', 'r') # Open file in reading mode
print(myFile.read()) # Prints out file
myFile.close() # Close file
myNewFile = open('newFile.txt', 'w') # Overwrites file OR creates new file
myNewFile.write('This is a new line') # Adds line to text
myNewFile.close()
file = open('newFile.txt', 'a') # Opens existing newFile.txt
file.write('This line has been added') # Add line (without overwriting)
file.close()
my_file = open("C:UsersPythonfile.txt", "w")
#Give the path accurately and use
my_file.write("This is the test text")
my_file.close()
# It is always recommended to close the file after modifying
# to see the output, open the file - file.txt