Write to a file in Python
This post will discuss how to write to a file in Python.
1. Using open() function
A simple solution is to open the file in write mode ('w') using the built-in open() function, which opens it for writing after truncating it. The file is created if it does not exist. Here’s what the code would look like:
|
1 2 3 4 |
f = open('file.txt', 'w') f.write('Hello, World\n') f.close() |
The above syntax explicitly closes the file handler with the close() function, and you might need to try-finally block for exception handling. It is good practice to use the with keyword, which automatically closes the file once it is done with, even when an exception is raised. Here’s an equivalent code using the with statement:
|
1 2 3 |
with open('file.txt', 'w') as f: f.write('Hello, World\n') |
Alternatively, you can open the file 'w+' mode, which opens it for both reading and writing:
|
1 2 3 |
with open('file.txt', 'w+') as f: f.write('Hello, World\n') |
⮚ Using'a' mode
If you need to append text at the end of the file if it exists, you can open it in the append mode ('a'). The file is created if it does not exist.
|
1 2 3 |
with open('file.txt', 'a') as f: f.write('Hello, World\n') |
The stream is always positioned at the end of the file in 'a' mode. Additionally, if you need to read text from the file, use the 'a+' mode.
|
1 2 3 |
with open('file.txt', 'a+') as f: f.write('Hello, World\n') |
2. Using pathlib module
With Python 3.4, you can also use the pathlib module. The Path.write_text() function opens the file in text mode, write data to it, and close the file.
|
1 2 3 |
import pathlib pathlib.Path('file.txt').write_text('Hello, World\n') |
3. Using io module
Another option is to use the io.open() function, which is an alias for the built-in open() function.
|
1 2 3 4 5 |
import io with io.open("file.txt", mode='w', encoding='utf-8') as f: f.write('Hello, World\n') |
That’s all about writing to a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)