Main Tutorials

How to write a file in Python

This article shows how to write a text file in Python.

Table of contents

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:

  1. Working with two files.
  2. Reading from a file.
  3. Modifying the content.
  4. 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

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments