Use the file Open() function with the “w” letter in our argument to create and write to file in Python. “w” indicates Python write to file and it will create a file in Python if it does not exist in the library.
f = open(path_to_file, mode)
f = open("test.txt","w+")
'w'
– open a file for writing. If the file doesn’t exist, the open()
function creates a new file. Otherwise, it’ll overwrite the contents of the existing file.
'x'
– open a file for exclusive creation. If the file exists, the open()
function raises an error (FileExistsError
). Otherwise, it’ll create the text file.
Python creates and writes to file example
Simple example code.
f = open("new.txt", "w+")
for i in range(5):
f.write("This is line %d \n" % (i + 1))
f.close()
Output:
Another example, the following creates a new file called readme.txt
and write some text into it:
with open('readme.txt', 'w') as f:
f.write('Create a new text file!')
Using the try-except statement
try:
with open('docs/readme.txt', 'w') as f:
f.write('Create a new text file!')
except FileNotFoundError:
print("The 'docs' directory does not exist")
Do comment if you have any doubts or suggestions on this Python write file topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.