Python中文本文件读取的方法有以下几种:
file = open('file.txt', 'r')
content = file.read()
file.close()
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)
这些方法可以根据具体的需求选择使用,可以满足大部分的文件读取操作。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: pycharm怎么新建一个python项目