码迷,mamicode.com
首页 > 编程语言 > 详细

Python逐行读取文件内容

时间:2020-03-31 23:02:07      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:import   hello   lan   对象   class   coding   覆盖   highlight   end   

一、使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。

二、需要导入import os

三、下面是逐行读取文件内容的三种方法:

1、第一种方法:

[python] view plain copy

  

技术图片
f = open("foo.txt")               # 返回一个文件对象   
line = f.readline()               # 调用文件的 readline()方法   
while line:   
    print line,                   # 后面跟 ‘,‘ 将忽略换行符   
    #print(line, end = ‘‘)       # 在 Python 3 中使用   
    line = f.readline()   
   
f.close()
技术图片

 


2、第二种方法:
  与第3种方法对比, 并非一次性将全部的文件内容载入到内存里,而是在迭代的时候,循环到哪一行才将哪一行读入内存。这里涉及到一个新的概念-迭代器。
  第二种方法是文本文件读取的最佳选择,它简单,且对任意大小的文件都有效,因为他不会一次性把整个文件都载入到内存里,相反第三种方法存在内存压力过大的问题。
for line in open("foo.txt"):   
    print line,    

 


3、第三种方法:
  
f = open("c:\\1.txt","r")   
lines = f.readlines()      #读取全部内容 ,并以列表方式返回  
for line in lines   
    print line 

 

四、一次性读取整个文件内容:

 

  

file_object = open(thefile.txt)  
try:  
     all_the_text = file_object.read()  
finally:  
     file_object.close()

 


五、区别对待读取文本 和 二进制:

1、如果是读取文本

  
    读文本文件  
    input = open(data‘, r)  
    #第二个参数默认为r  
    input = open(data‘)  

 


2、如果是读取二进制
 
  
input = open(data‘, rb‘)  

 

 读固定字节

 

chunk = input.read(100)

 

python3 按行读取并进行编辑
            
             def test(file):    with open(file, ‘r+‘) as a:        with open(file, ‘r+‘) as b:            for line in a:                b.write(‘hello ‘ + line)

1、文件打开格式不一定是“r+”,但是必须指针落点从头开始,所有不能说“a”,因为“w”会把源文件内容清空,也不行

第一个文件打开格式可以是:r,r+

第二个文件打开格式可以是:r+

2、文件必须open两次,因为每一次指针落点都要从头开始

3、r+模式write时会覆盖原来内容,但是

在文件关闭前或缓冲区刷新前,字符串内容存储在缓冲区中,这时你在文件中是看不到写入的内容的。
————————————————

 

需要安装xlwt库,可以用如下命令安装:
pip install xlwt
1
示例文本:
100 -494 td_error 0.6692215
200 318 td_error 0.57682794
300 57 td_error 0.45037615
400 260 td_error 0.42214713
500 586 td_error 0.45073098
600 615 td_error 0.4728373
700 731 td_error 0.48083866
800 802 td_error 0.3751492
900 440 td_error 0.4249844
1000 430 td_error 0.36427215
12345678910
参考代码:
import xlwt
import codecs

input_txt = ‘demo.txt‘
output_excel = ‘demo.xls‘
sheetName = ‘Sheet1‘
start_row = 0
start_col = 0

wb = xlwt.Workbook(encoding = ‘utf-8‘)
ws = wb.add_sheet(sheetName)

f = open(input_txt, encoding = ‘utf-8‘)

row_excel = start_row
for line in f:
    line = line.strip(‘\n‘)
    line = line.split(‘ ‘)
   
    print(line)

    col_excel = start_col
    len_line = len(line)
    for j in range(len_line):
        print (line[j])
        ws.write(row_excel,col_excel,line[j])
        col_excel += 1
        wb.save(output_excel)

    row_excel += 1

f.close
1234567891011121314151617181920212223242526272829303132
代码执行完后,会生成一个excel文件
————————————————

Python逐行读取文件内容

标签:import   hello   lan   对象   class   coding   覆盖   highlight   end   

原文地址:https://www.cnblogs.com/xinxihua/p/12609092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
分享档案
周排行
mamicode.com排行更多图片
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!