How to write to a file in Python using open() with mode 'w' or 'a'?
Published on Aug. 22, 2023, 12:17 p.m.
To write to a file in Python using the open()
function with mode ‘w’ or ‘a’, you can follow these steps:
- Open the file in write (‘w’) or append (‘a’) mode using the
open()
function, specifying the file path and mode as parameters. If the file does not exist, it will be created in ‘w’ mode.
file = open('example.txt', 'w') # 'a' for append mode
- Use the
write()
method on the file object to write the desired content to the file. You can write a single line or multiple lines, separated by the newline character (‘\n’).
file.write('Hello, world!\n')
file.write('This is some more text.\n')
- After writing all the content, close the file using the
close()
method on the file object to ensure that all data is saved.
file.close()
Alternatively, you can use the with
statement to automatically close the file when you are done writing to it:
with open('example.txt', 'w') as file:
file.write('Hello, world!\n')
file.write('This is some more text.\n')
This automatically closes the file when the with
block is exited.
In summary, you can write to a file in Python using the open()
function with mode ‘w’ or ‘a’, followed by the write()
method to write content and the close()
method to close the file. Alternatively, you can use the with
statement to automatically close the file.