Now that we have a newly-created file in Python, we can use the write() function to write content to that file. Let’s say we want to create a .txt (plain text) file and write a string to that file. We can do that using write().
Python Examples¶
# creates new txt file with write permission
f = open("new_file.txt", "w")
# writes string to new file
f.write("Hello world!")
# closes file
f.close()NOTE: It is very important to
close()the file once you are done writing content or making modifications.
Another example where we have assigned a string to a variable and write the variable to the .txt file:
# creates new txt file with write permission
f = open("new_file.txt", "w")
# assigns string to variable
hello_world = "Hello world!"
# writes string variable to new file
f.write(hello_world)
# closes file
f.close()# alternate workflow for the same program, using with open
with open("new_file.txt", "w") as f:
f.write("Hello world!")We can open the new_file.txt file to see the newly-added content.
Additional Resources¶
For more on file handling methods in Python: