python file write and read code example
Example 1: python write file
with open("file.txt", "w") as file:
for line in ["hello", "world"]:
file.write(line)
Example 2: how to write a python variable to a file
import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'w')
pickle.dump(dict, file)
file.close()
file = open('dump.txt', 'r')
dict = pickle.load(file)
Example 3: read and write to file python
file = open(“testfile.txt”, “r+”)
Example 4: how to open a text file in python
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Example 5: Python File Write
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
f = open("demofile3.txt", "r")
print(f.read())