我有一个标题行需要在文本文件的开头打印,然后下一行应该包含有关有多少行数据的信息。
最终输出文件应包含以下内容:
- 第一个
n
之前的标题行 - 文件的长度(即第 2 个
n
之前的行 # - 字符串的未知行
问题是,如果不首先知道有多少行字符串,如何满足(2(内容?
我一直在这样做:
- 编写标题行
- 写一行 50
" "
个字符的假行 - 写入未知的字符串行,同时保持计数器 #lines
- 查找到标题行的末尾
- 将 #line 行写在第二行中,其余
" "
保持不变 - 关闭文件(想象一下它高达19GB的字符串(
举个例子,我用random.random()
来生成行数,我一直是这样做的:
import random
fout = open('testoverwrite','w')
header = "%% this is a header line"
print>>fout, header
print>>fout, "".join((" ")*50)
total = 0
numrows = int(100*random.random())
for i in range(numrows):
j = int(100*random.random())
total+=j
print>>fout, j
fout.seek(len("%% this is a header linen"))
#print len(str(numrows)+" "+str(total))
if len(str(numrows)+" "+str(total)) < 50:
fout.write(str(numrows)+" "+str(total))
fout.close()
有没有更好的方法可以做到这一点?
好吧,我不明白你为什么要这样做,但如果你必须这样做;-( 为了使其跨平台工作,seek()
并不总是像您认为的那样在以文本模式打开的文件上工作。 要使其在文本模式文件上可靠地工作,您只能seek()
tell()
之前返回的位置。 因此,在编写标题行后,请执行(例如(:
print>>fout, header
pos = fout.tell()
此时pos
可能等于也可能不等于len(header) + 1
(取决于平台(。 但是稍后寻求它将到达标题后面的行的开头。 因此,请替换您的:
fout.seek(len("%% this is the header linen"))
(无论如何,这很奇怪,因为这不是您之前写的标题行(:
fout.seek(pos)
然后,下一次写入将覆盖文件第二行中的前导字符。