Several ways of processing text files in Python

1. Read the file

There are three commonly used functions for reading files in python: read(), readline(), and readlines()

1. Read all

file = open('textfile.txt', 'r')
content = file.read()  # 所有内容保存在content中
file.close()
# 使用上下文管理器读取文件内容
with open('textfile.txt', 'r') as file:
    content = file.read()

2. Read line by line

file = open('textfile.txt', 'r')
for line in file:
    print(line)		# 打印每行内容
file.close()
file = open("textfile.txt", "r")  # 以只读模式打开文件
 
lines = file.readlines()  # 获取所有行并保存到lines列表中
 
row = 8  # 指定开始读取的行
for line in lines[row-1:]:  # 读取指定的所有行
    line.strip('\n')  # 去掉换行符
    data = line.split()  # 去掉空格
    print(data)
f.close()  # 关闭文件

2. Write to the file

file = open('textfile.txt', 'w')
file.write('Hello, World!')
file.close()
# 使用上下文管理器写入文件内容
with open('textfile.txt', 'w') as file:
    file.write('Hello, World!')

3. Additional content

# 打开文件以追加内容
with open('textfile.txt', 'a') as file:
    file.write('This is some appended content.\n')

4. Appendix

  • r: read the file, if the file does not exist, an error will be reported

  • w: Write to the file, if the file does not exist, it will be created first and then written, and the original file will be overwritten

  • a: Write to the file, if the file does not exist, it will be created first and then written, but the original file will not be overwritten, but will be appended at the end of the file

  • rb, wb: Similar to r and w respectively, but for reading and writing binary files

  • r+: Readable and writable, an error will be reported if the file does not exist, and it will be overwritten when the file is written

  • w+: Readable, writable, if the file does not exist, create it first, and it will be overwritten

  • a+: Readable and writable, if the file does not exist, it will be created first, it will not be overwritten, and it will be appended at the end

Guess you like

Origin blog.csdn.net/hfy1237/article/details/131108699