程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

python读取文件的几种方式

hfteth 2025-01-06 21:46:39 技术文章 12 ℃

方法一

f = open('1.txt')

while True:

line = f.readline()

if not line: break

print(line, end='')

每次读取一行,可以用f.tell()来指出当前即将读取的位置

方法二

f = open('1.txt')

while True:

try:

print(next(f), end='')

except StopIteration:

break

等价于

f = open('1.txt')

while True:

try:

print(f.__next__(), end='')

except StopIteration:

break

每次迭代一行,不可使用f.tell()取出当前位置

方法三

for line in open('1.txt'):

print(line, end='')

for自动进行每次迭代一行,效率高,推荐

方法四

for line in open('1.txt').readlines():

print(line, end='')

一次读取文件全部内容,然后一次取一行,文件大容易撑爆内存

Tags:

最近发表
标签列表