Python Write/Create Files
To write or create a new file, use the open()
function with the 'w'
or 'a'
mode. Write mode ('w'
) will overwrite the file, while append mode ('a'
) will add content to the end of the file.
Example: Writing to a File
# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, this is a new file created using Python.')
print('File written successfully!')
Output
File written successfully!
Explanation: This example demonstrates how to open a file in write mode, write data to it, and close the file.