方法一:redline函数
f = open ( "/pythontab/code.txt" ) # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
#print line, # 在 Python 2中,后面跟 ',' 将忽略换行符
print (line, end = '') # 在 Python 3中使用
line = f.readline()
f.close()
方法二:一次加载多行
f = open ( "/pythontab/code.txt" )
while 1 :
lines = f.readlines( 10000 )
if not lines:
break
for line in lines:
print (line)
f.close()
方法三:for循环读取
for line in open ( "/pythontab/code.txt" ):
#print line, #python2 用法
print (line)
方法四:使用fileinput模块
import fileinput
for line in fileinput. input ( "/pythontab/code.txt" ):
print (line)
本文介绍了Python中四种常见的文件读取方法:使用readline()逐行读取,一次性加载多行,for循环遍历文件,以及利用fileinput模块。详细讲解了每种方法的实现代码和使用场景,帮助开发者更高效地操作文件。
849

被折叠的 条评论
为什么被折叠?



