SoFunction
Updated on 2025-03-01

Summary of five ways to write content into a file in Python

1. Write() method

Use the write() method: Use the open() function to open the file, and then use the write() method to write the content to the file. For example:

with open('', 'w') as f:
    ('Hello, world!')

The open() function is a built-in function for opening files in Python. Its common parameters and their meanings are as follows:

: File name or file path. It can be an absolute path or a relative path. If it is a relative path, it is relative to the current working directory. If the path is omitted, the file is opened in the current working directory.

: File opening mode. It can be one of the following values:

  • 'r': Read-only mode. Default mode, if the file does not exist, an exception will be raised.
  • 'w': Write mode. If the file does not exist, create the file. If the file already exists, clear the file and write new content.
  • 'x': Exclusive creation mode. If the file does not exist, create the file. If the file already exists, an exception is raised.
  • 'a': Append mode. If the file does not exist, create the file. If the file already exists, add new content to the end of the file.
  • 'b': Binary mode. Use with other modes, such as 'rb' or 'wb'.
  • 't': Text mode. Use with other modes, such as 'rt' or 'wt'.

: Set the size of the buffer. If omitted or is 0, no buffering is performed. If 1, line buffering. If it is greater than 1, it is the buffer size.

: Encoding format used to encode and decode file contents. If omitted, use the default encoding.

: How to deal with errors when encoding and decoding file contents. It can be one of the following values:

  • 'strict': Default value, indicating that an exception was thrown when an error was encountered.
  • 'ignore': Ignore errors.
  • 'replace': Replace the wrong character with '?'.
  • 'backslashreplace': Replace the wrong character with backslash escape.
  • 'xmlcharrefreplace': Replace the wrong character with an XML entity.
  • 'namereplace': Replace the wrong character with \N{...} escape.

: Controls the processing of line breaks in text mode. It can be one of the following values:

  • None: Use the default line break \n.
  • '': No newline conversion is performed.
  • '\n', '\r', '\r\n', '\u2028', '\u2029': Use the specified newline character.

: If True, it means that its underlying file descriptor will be closed when the file is opened. Default is True.

: Custom function or class used to open a file. Default is None.

These parameters can be used in different combinations to meet different operational requirements for files. For example, open('', 'w') opens a file named , in write mode, and creates a new empty file if the file does not exist.

2. Writelines() method

The writelines() method writes a list of strings to a file. For example:

with open('', 'w') as f:
    lines = ['Hello, world!', 'Welcome to Python']
    (lines)

The writelines() method is a method used to write a list of strings to a file. But the following points need to be paid attention to:

  • The writelines() method only accepts a list of strings as arguments. If you want to write a single string, use the write() method.
  • The writelines() method does not automatically add newlines between strings and needs to be added manually to the string.
  • The writelines() method does not add empty lines at the end of the list. If you need to add empty lines to the last line, manually add an empty string containing a newline.
  • When using the writelines() method, you need to ensure that the passed parameters are a list of strings. If the parameter is a generator object, it needs to be converted into a list and passed.
lines = ['line 1\n', 'line 2\n', 'line 3\n']
 
with open('', 'w') as f:
    (lines)

The advanced usage of the method is mainly to write data from the iterator object to a file without converting it to a list at once. This usage is useful for large data sets because it iterates over elements one by one, avoiding storing all elements in memory.

def generate_lines():
    yield 'line 1\n'
    yield 'line 2\n'
    yield 'line 3\n'
 
with open('', 'w') as f:
    (generate_lines())

In the above code, the generate_lines() function returns an iterator object that generates strings one by one. Then, pass this iterator object to the writelines() method, which writelines() method writes strings in the iterator object to the file one by one.

3. print() function

You can use the print() function to write content to a file, and you need to specify the file parameter as the open file object. For example:

with open('', 'w') as f:
    print('Hello, world!', file=f)

The following are the common parameters of the print() function and their detailed introduction:

The print() function is a built-in function in Python for printing out information to the terminal. The print() function can take multiple parameters and print them to the terminal.

The following are the common parameters of the print() function and their detailed introduction:

print(*objects, sep=' ', end='\n', file=, flush=False)

  • *objects: One or more objects to be printed out, which can be strings, numbers, variables, etc. Any number of parameters can be accepted.
  • sep: A character used to separate multiple parameters, default is a space. When multiple parameters are printed out, the sep parameter will serve as a separator between them.
  • end: A character used to indicate the end of the printout, and the default is a newline character. After printing out the last parameter, the end parameter will be used as the character after them.
  • file: The file object used to specify the output, the default is a standard output device. The output can be redirected to a file so that the output can be saved to a file instead of a terminal.
  • flush: Used to specify whether to refresh the buffer immediately, default is False. If the flush parameter is set to True, the output is written to the file immediately, rather than waiting for the buffer to be full before writing.
# Print out a single stringprint("Hello World")
 
# Print out multiple parametersprint("Name:", "John", "Age:", 25)
 
# Use custom delimitersprint("Name:", "John", "Age:", 25, sep="-")
 
# Use custom ending charactersprint("Name:", "John", "Age:", 25, end=".")
 
# Redirect output to filewith open('', 'w') as f:
    print("Hello World", file=f)
 
# Refresh the buffer immediatelyprint("Hello World", flush=True)

print(string, *args, **kwargs)

  • string: Format string containing the information to print out and formatted placeholders. The formatted placeholder is wrapped in curly braces {} and specifies the type, width, precision and other information of the data to be filled.
  • *args: Optional parameter containing data to be populated into the formatted string.
  • **kwargs: Optional parameter containing key-value pairs to specify the value of the placeholder in the formatted string.
name = "John"
age = 25
 
# Use placeholders to output stringsprint("Name: {}, Age: {}".format(name, age))
 
# Use keyword parameters to output stringsprint("Name: {n}, Age: {a}".format(n=name, a=age))
 
# Use f-string to output stringsprint(f"Name: {name}, Age: {age}")

4. Use the csv module

The data can be written to a CSV file using the csv module. For example:

import csv
 
with open('', 'w', newline='') as f:
    writer = (f)
    (['Name', 'Age', 'Gender'])
    (['Alice', 25, 'F'])
    (['Bob', 30, 'M'])

5. Use json module

Python objects can be written to JSON files using the json module. For example:

import json
 
data = {
    'name': 'Alice',
    'age': 25,
    'gender': 'F'
}
 
with open('', 'w') as f:
    (data, f)

This is the end of this article about five methods to write content into files by Python. For more related Python content to write content into files, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!