Skip to main content
python write to text file

Write Text File Using Python 3

in this python tutorial, I’ll show you Writing a text file using python. Python has built-in file writing method to open and write content into the file. There are two sorts of files that can be used to write: text files and binary files.

We ll following steps to write a file in python:

  • We’ll open a file using open() function.
  • Write the content into the text files using write() or writelines() method.
  • Finally, Close the file using close() function.

You can also checkout other python file tutorials:

How To Write Text File

The following code help to write a string into the text file.

with open('text.txt', 'w') as f:
f.write('text')

In the above code:

with : We have opened file using with statement. The with statement help to close the file automatically without calling the close() method.

without with, you need to explicitly call close() method to close the file.

open: The method helps to open a text file in write( or append) mode. The open() method returns a file object, And the file object has two useful methods for writing text to the file: write() and writelines().

The syntax is:

open(path_to_file, mode)

Where is parameter is:

  • path_to_file : This is the file’s location. It might be the current directory or the path.
  • mode : There are 6 access modes in python.This help to
ModeDescription
'w'Open a file for writing text.
'w+'Open a file for writing and reading text.data is truncated and over-written for already exist file
'a'Open a text file for appending text
'a+'Open a text file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.

The write() method writes a string to a text file and the writelines() method write() a list of strings to a file at once.

The writelines() method accepts an iterable object, not just a list, so you can pass a tuple of strings, a set of strings, etc., to the writelines() method.

To write a line to a text file, you need to manually add a new line character:

f.write('\n')
f.writelines('\n')

How To Write UTF-8 text files Using Python

The above code example will work with ASCII Text type files. However, if you’re dealing with other languages such as Chinese, Japanese, and Korean files, those are UTF-8 type files.

To open a UTF-8 text file, You need to pass the encoding=’utf-8′ to the open() function.

quote = "你好,我是标准杆"
with open('tesr.txt', 'w', encoding='utf8') as file:
lines = file.write(quote)

One thought to “Write Text File Using Python 3”

Leave a Reply

Your email address will not be published. Required fields are marked *