#!/usr/bin/env python
# -*- coding: utf-8 -*-
def updat_file(ss):
with open('test.txt', 'w', encoding='utf-8') as f:
f.write('\r\n'.join(ss))
k = 0
if __name__== "__main__" :
while k < 6:
with open('test.txt', 'r', encoding='utf-8') as f:
ss = [i[0:7] for i in f.readlines()]
ss.pop(0)
updat_file(ss)
k += 1
write函数在写入时会把'\r\n'处理为两个换行符,那就解释得通我实际碰到的问题了,只是似乎又不是每次都这样,所以我不得不在生产程序中添加一个条件检测条目是否为空,原始数据文件没有空行,每次读取后马上用 rstrip 而不是切片去换行,但有时候文件会出现空行,但程序中对列表除了 pop 和在函数间传来传去,没有其他操作
def readlines(self, hint=None):
"""Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
"""
if hint is None or hint <= 0:
return list(self)
n = 0
lines = []
for line in self:
lines.append(line)
n += len(line)
if n >= hint:
break
return lines
20048 ~tmp
>>> python -m timeit -s 'a = "123456\n"' 'a.strip()'
5000000 loops, best of 5: 47.7 nsec per loop
20049 ~tmp
>>> python -m timeit -s 'a = "123456\n"' 'a[0:7]'
5000000 loops, best of 5: 46.8 nsec per loop
20050 ~tmp
>>> python -m timeit -s 'a = "123456\n"' '"" if a == "\n" else a[0:7]'
5000000 loops, best of 5: 64.6 nsec per loop