how to write to a text file in python code example
Example 1: python read file to variable
with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')
Example 2: python writing to text file
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
Example 3: 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 4: python open and reacd file
with open('yourfile.txt','r') as f:
lines = f.readlines()
f.close()
Example 5: python write file
with open("file.txt", "w") as file:
for line in ["hello", "world"]:
file.write(line)
Example 6: how to write to a text file in python
from sys import *
f = open("haha.txt", "w")
f.write(str(argv[1]))
f.close()
f = open("haha.txt", "r")
print(f.read())