python write in a text file code example

Example 1: python writing to text file

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())

Example 2: python write to file

file = open(“testfile.txt”,”w”) 
 
file.write(“Hello World”) 
file.write(“This is our new text file) 
file.write(and this is another line.) 
file.write(“Why? Because we can.) 
 
file.close()

Example 3: python write to file

with open(filename,"w") as f:
  f.write('Hello World')

Example 4: python write to file

with open("hello.txt", "w") as f:
	f.write("Hello World")
#using With Statement files opened will be closed automatically