Python Text File Editing Tutorial

To modify the content of a txt file, you can use the following code example:

# 打开文件
with open('example.txt', 'r') as file:
    data = file.readlines()

# 修改文件内容
data[0] = 'New content\n'

# 写回文件
with open('example.txt', 'w') as file:
    file.writelines(data)

In this example, we firstly open a file named example.txt using the with open() statement and read the file content into a list. Then, we modify the content in the list, changing the content of the first line to “New content”. Finally, we open the file again using the with open() statement and write the modified content back to the file.

bannerAds