A summary of Python's methods for writing content to files.

       Using Python to write files is our coder's daily life. This article will take you through the method and details of how python writes content to files. Mainly include write() method, writelines()method, print()function, use csvmodule , use jsonmodule.

Table of contents

 1. write() method

Two, writelines () method

3. print() function

Fourth, use the csv module

 5. Use the json module


 1. write() method

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

with open('example.txt', 'w') as f:
    f.write('Hello, world!')

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

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

  2. mode: file open mode. Can be one of the following values:

    • 'r': Read-only mode. The default mode, throws an exception if the file does not exist.
    • 'w': Write mode. If the file does not exist, the file is created. If the file already exists, the file is emptied and new content is written.
    • 'x': Exclusive creation mode. If the file does not exist, the file is created. Raises an exception if the file already exists.
    • 'a': append mode. If the file does not exist, the file is created. If the file already exists, the new content is appended to the end of the file.
    • 'b': Binary mode. Used with other patterns such as 'rb'or 'wb'.
    • 't': Text mode. Used with other patterns such as 'rt'or 'wt'.
  3. buffering: Set the size of the buffer. If omitted or 0, no buffering takes place. If 1, line buffering. If greater than 1, the buffer size.

  4. encoding: The encoding format used to encode and decode the file content. If omitted, the default encoding is used.

  5. errors: How to handle errors encountered while encoding and decoding file content. Can be one of the following values:

    • 'strict': The default value, which means that an exception is thrown when an error is encountered.
    • 'ignore': Ignore errors.
    • 'replace': '?'Replace wrong characters with .
    • 'backslashreplace': Replace wrong characters with backslash escapes.
    • 'xmlcharrefreplace': Replace wrong characters with XML entities.
    • 'namereplace': Replace wrong characters with \N{...}escapes .
  6. newline: Controls how line breaks are handled in text mode. Can be one of the following values:

    • None: Use default line breaks \n.
    • '': No newline conversion.
    • '\n', '\r', '\r\n', '\u2028', '\u2029': Use the specified newline character.
  7. closefd: If true True, indicates that the file's underlying file descriptor will be closed when it is opened. Default is True.

  8. opener: A custom function or class for opening a file. Default is None.

     These parameters can be used in different combinations to meet different operating needs on the file. For example, a file named open('example.txt', 'w') will be opened in write mode , or a new empty file will be created if the file does not exist.example.txt

2. writelines()Method

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

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

      writelines()method is the method used to write the list of strings to the file. But you need to pay attention to the following points: 

  1. writelines()method accepts only a list of strings as parameters. If you want to write a single string, use write()the method .

  2. writelines()method does not automatically add line breaks between strings, you need to manually add them to the string.

  3. writelines()method will not add a blank line at the end of the list, if you need to add a blank line at the last line, please manually add an empty string containing a newline.

  4. When using writelines()the method , you need to ensure that the passed parameter is a list of strings. If the parameter is a generator object, it needs to be converted to a list before passing.

lines = ['line 1\n', 'line 2\n', 'line 3\n']

with open('example.txt', 'w') as f:
    f.writelines(lines)

        Advanced usage of the method is mainly to write the data in the iterator object to a file without converting it to a list all at once. This usage is useful for large collections of data, as 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('example.txt', 'w') as f:
    f.writelines(generate_lines())

        In the above code, generate_lines()the function returns an iterator object which yields strings one by one. Then, this iterator object is passed to writelines()the method , writelines()and the method writes the strings in the iterator object to the file one by one.

3. print()Function

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

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

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

print()function is a built-in function in Python for printing output information to the terminal. print()Functions can accept multiple arguments and print them to the terminal.

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

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

*objects: One or more objects to be printed out, which can be strings, numbers, variables, etc. Can accept any number of arguments.

sep: The character used to separate multiple parameters, the default is a space. When printing out multiple parameters, septhe parameter will be used as a separator between them.

end: The character used to indicate the end of the printout, the default is a newline character. endArguments are taken as the characters after them after the last argument is printed out .

file: The file object used to specify the output, the default is the standard output device sys.stdout. The output can be redirected into a file so that the output is saved to the file instead of the terminal.

flush: Used to specify whether to flush the buffer immediately, the default is False. If flushthe parameter is set to True, the output will be written to the file immediately instead of waiting for the buffer to be full.

# 打印输出单个字符串
print("Hello World")

# 打印输出多个参数
print("Name:", "John", "Age:", 25)

# 使用自定义分隔符
print("Name:", "John", "Age:", 25, sep="-")

# 使用自定义结束符
print("Name:", "John", "Age:", 25, end=".")

# 将输出重定向到文件
with open('output.txt', 'w') as f:
    print("Hello World", file=f)

# 立即刷新缓冲区
print("Hello World", flush=True)

print(string, *args, **kwargs)

string: Formatting string, which contains the information to be printed out and formatting placeholders. Formatting placeholders are {}wrapped and specify the type, width, precision and other information of the data to be filled.

*args: Optional parameter containing the data to fill into the formatted string.

**kwargs: An optional parameter, containing key-value pairs, used to specify the value of the placeholder in the format string.

name = "John"
age = 25

# 使用占位符输出字符串
print("Name: {}, Age: {}".format(name, age))

# 使用关键字参数输出字符串
print("Name: {n}, Age: {a}".format(n=name, a=age))

# 使用 f-string 输出字符串
print(f"Name: {name}, Age: {age}")

Fourth, use csvthe module

        Data can be written to a CSV file using csvthe module . For example:

import csv

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

 5. Use jsonthe module

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

import json

data = {
    'name': 'Alice',
    'age': 25,
    'gender': 'F'
}

with open('example.json', 'w') as f:
    json.dump(data, f)

Guess you like

Origin blog.csdn.net/weixin_44120785/article/details/129106587