How to use Python to read and write txt files

In Python, we can use built-in functions to read and write text files. Here are some basic operations:

read text file

We can use Python's built-in open()function to open a text file. open()The function needs to pass two parameters. The first parameter is the file path and file name, and the second parameter is the mode of opening the file. Common modes include rread-only mode and wIndicates write mode. Here is a sample code for reading a text file:

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

write to text file

We can use Python's built-in open()function to open a text file. open()The function needs to pass two parameters. The first parameter is the file path and file name, and the second parameter is the mode of opening the file. Common modes include rread-only mode and wIndicates write mode. Here is a sample code that writes to a text file:

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

In the above code, we withhave opened a example.txtfile named using the statement and written wa string Hello, world!to the file using the pattern.

append text file

If we need to append new content to a text file, we can aopen the file using a mode, as follows:

with open('example.txt', 'a') as file:
    file.write('\\nThis is a new line.')

In the above code, we withhave opened a example.txtfile called using the statement and using athe pattern to This is a new line.write the string to a new line in the file.

Guess you like

Origin blog.csdn.net/xili1342/article/details/130085539