0
点赞
收藏
分享

微信扫一扫

python逐行读取文件内容的方法

古得曼_63b6 2022-02-13 阅读 83

文章目录

方法一: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)
举报

相关推荐

0 条评论