open a file and write to it python code example
Example 1: 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 2: python how to make a file to write to
file_object = open("filename", "mode")
file_object.write("Data to be written")
file_object.close()
file_object = open("/path/to/my_filename.txt", "w")
file_object.write("Line of text to write")
file_object.close()
Example 3: how write to file in python
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
Example 4: read and write to file python
file = open(“testfile.txt”, “r+”)
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())