How to write a file in Python
This article shows how to write a text file in Python.
Table of contents
- 1. Write to a file – open() and close()
- 2. Write to a file – with statement
- 3. Write multiple lines to a file
- 4. Working with two files
- 5. Find and replace in a file
- 6. Download Source Code
- 7. References
P.S Tested with Python 3.8
1. Write to a file – open() and close()
The open mode w
creates a new file or truncates an existing file
, then opens it for writing
; the file pointer position at the beginning of the file.
P.S Truncate means remove the file content.
f = open('file-new.txt', 'w')
f.write("test 1\n")
f.write("test 2\n")
f.close
Output
file-new.txt
test 1
test 2
2. Write to a file – with statement
We can use the with
statement to close the file automatically.
with open('file-new.txt', 'w') as f:
f.write("test 1 \n")
f.write("test 2 \n")
f.write("test 3 \n")
Output
file-new.txt
test 1
test 2
test 3
3. Write multiple lines to a file
We can use writelines()
to write multiple lines or a list
to a file.
data = ["test 1 \n", "test 2 \n", "test 3 \n"]
with open('file-new.txt', 'w') as f:
f.writelines(data)
Output
file-new.txt
test 1
test 2
test 3
4. Working with two files
The below example includes:
- Working with two files.
- Reading from a file.
- Modifying the content.
- Writing the modified content into another file.
file.txt
test 1
test 2
test 3
with open('file.txt', 'r') as input, open('file-modify.txt', 'w') as output:
lines = input.readlines()
output.writelines(lines[1:]) # skip first line and write to output
Output
file-modify.txt
test 2
test 3
5. Find and replace in a file
The below example shows how to find and replace a string in a file.
file.txt
test 1
test 2
test 3
with open('file.txt', 'r') as f: # read a file
lines = f.read()
lines = lines.replace('test', 'hello') # replace string
with open('file.txt', 'w') as f: # write to file
f.write(lines)
Output
Terminal
hello 1
hello 2
hello 3
6. Download Source Code
$ git clone https://github.com/mkyong/python
$ cd io
7. References
About Author
Comments
Subscribe
0 Comments