Python | read()、readline()和readlines()的用法区别

标签:python

需要提取的数据为:

i:I love seajay
from:AUTO
to:AUTO
smartresult:dict
client:fanyideskweb
salt:15483356026163
sign:0e6fc7b099ab52173b750e4f1fe2e967
ts:1548335602616
bv:563490a3a59c96d89a5868bde7ab81c1
doctype:json
version:2.1
keyfrom:fanyi.web
action:FY_BY_CLICKBUTTION
typoResult:false

将以上数据另存为“原始数据.txt”

1. read()的使用

>>> data = {}
    filename = "原始数据.txt"
>>> with open(filename) as f:
    print(f.read())

i:I love seajay
from:AUTO
to:AUTO
smartresult:dict
client:fanyideskweb
salt:15483356026163
sign:0e6fc7b099ab52173b750e4f1fe2e967
ts:1548335602616
bv:563490a3a59c96d89a5868bde7ab81c1
doctype:json
version:2.1
keyfrom:fanyi.web
action:FY_BY_CLICKBUTTION
typoResult:false

或者

>>> data = {}
    filename = "原始数据.txt"
>>> with open(filename) as f:
    print(f.read(80))

i:I love seajay
from:AUTO
to:AUTO
smartresult:dict
client:fanyideskweb
salt:1548

2. readline()的使用

>>> with open(filename) as f:
    line = f.readline().rstrip()
    while line:
        print(line)
        line = f.readline().rstrip()
        
i:I love seajay
from:AUTO
to:AUTO
smartresult:dict
client:fanyideskweb
salt:15483356026163
sign:0e6fc7b099ab52173b750e4f1fe2e967
ts:1548335602616
bv:563490a3a59c96d89a5868bde7ab81c1
doctype:json
version:2.1
keyfrom:fanyi.web
action:FY_BY_CLICKBUTTION
typoResult:false

注意:需要在末尾加上.strip(),否则输出会包含\n回车符

3. readlines()的使用

>>> data = {}
    filename = "原始数据.txt"
>>> with open(filename) as f:
    print(f.readlines())
    
['i:I love seajay\n', 'from:AUTO\n', 'to:AUTO\n', 'smartresult:dict\n', 'client:fanyideskweb\n', 'salt:15483356026163\n', 'sign:0e6fc7b099ab52173b750e4f1fe2e967\n', 'ts:1548335602616\n', 'bv:563490a3a59c96d89a5868bde7ab81c1\n', 'doctype:json\n', 'version:2.1\n', 'keyfrom:fanyi.web\n', 'action:FY_BY_CLICKBUTTION\n', 'typoResult:false']
    原文作者:涤小生2019
    原文地址: https://www.jianshu.com/p/deaee0c3ab65
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞