文章目录
方法一: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)