python读取文件的方法

一、 通过readline 逐行读取:

#--encoding:utf-8
with open("ha.conf","r",encoding='utf-8') as f:
    print(f)
    print(f.encoding)
    strline = f.readline()
    while strline:
        print(strline)
        print(f.tell())
        strline = f.readline()

  open函数返回一个文件对象。有name、mode 和 encoding 属性。

以上代码返回如下:

D:Python34python.exe E:/PycharmProjects/Day3/file_operation.py
<_io.TextIOWrapper name='ha.conf' mode='r' encoding='utf-8'>
utf-8
global

8
        log 127.0.0.1 local2

38
        daemon

54
        maxconn 256

…………

  读取第一行 global 后,f.tell() 返回 8 : global 加上 换行 7个字符。 

二:

with open("ha.conf","r",encoding='utf-8') as f:
    for line in f:
         print(line)

  

原文地址:https://www.cnblogs.com/z360519549/p/5173827.html