Python中文本文件读取的方法有以下几种:
- 使用open函数打开文件并读取内容:
file = open('file.txt', 'r') content = file.read() file.close()
- 使用with语句自动关闭文件:
with open('file.txt', 'r') as file: content = file.read()
- 逐行读取文件内容:
with open('file.txt', 'r') as file: for line in file: print(line)
- 读取指定行数的内容:
with open('file.txt', 'r') as file: lines = file.readlines()[:5] # 读取前5行内容 for line in lines: print(line)
- 读取文件中的单词或者特定字符:
with open('file.txt', 'r') as file: content = file.read() words = content.split() # 分割成单词列表 for word in words: print(word)
这些方法可以根据具体的需求选择使用,可以满足大部分的文件读取操作。