Python从txt文件中逐行读取数据

Posted xiaopihaierletian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python从txt文件中逐行读取数据相关的知识,希望对你有一定的参考价值。

非常的简单,提供三种方法:

方法一:

[python]  view plain  copy  
  1. f = open("foo.txt")             # 返回一个文件对象  
  2. line = f.readline()             # 调用文件的 readline()方法  
  3. while line:  
  4.     print line,                 # 后面跟 ',' 将忽略换行符  
  5.     # print(line, end = '')   # 在 Python 3中使用  
  6.     line = f.readline()  
  7.   
  8. f.close()  

方法二:

[python]  view plain  copy  
  1. for line in open("foo.txt"):  
  2.     print line,  

方法三:

[python]  view plain  copy  
  1. f = open("c:\\\\1.txt","r")  
  2. lines = f.readlines()#读取全部内容  
  3. for line in lines  
  4.     print line  

收工

以上是关于Python从txt文件中逐行读取数据的主要内容,如果未能解决你的问题,请参考以下文章