在Python中,读取文本内容的方法有以下几种:
with open('file.txt', 'r') as file:
content = file.read()
print(content)
with open('file.txt', 'r') as file:
for line in file:
print(line)
n = 5
with open('file.txt', 'r') as file:
for i in range(n):
line = file.readline()
print(line)
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line)
with open('file.txt', 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()
这些是常用的读取文本内容的方法,根据具体需求选择合适的方法进行操作。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: python怎么计算并输出最长字符串