有人可以告诉我如何在使用 python 将行写入该文件后在文件顶部写入行数吗?
line_count=?
sam
john
gus
heisenberg
有人可以告诉我如何在使用 python 将行写入该文件后在文件顶部写入行数吗?
line_count=?
sam
john
gus
heisenberg
你不能那么简单地做到这一点。文件是一个字节序列。您必须首先确保在编写所有这些行时,将它们写到它们的最终位置。最简单的方法是在您第一次写入文件时为您的行数“保留”空间。正如您在描述中所做的那样,编写整个文件,但为行数保留“占位符”空间。例如,如果文件中最多有 9999 行,则为该计数保留四个字节:
line_count=????
sam
john
gus
heisenberg
seek(11)
完成所有行的写入后,使用和file.write()
计数备份到文件中的适当字节位置(字节 11-14) ,格式化为四个字符。
我假设您已经知道如何将行写入文件,以及如何格式化整数。您所缺少的只是基本逻辑和seek
方法。
给你!
text = open("textfile.txt").readlines()
counter = 0
for row in text:
counter += 1 # just snags the total amount of rows
newtext = open("textfile.txt","w")
newtext.write(f"line_count = {counter}\n\n") # This is your header xoxo
for row in text:
newtext.write(row) # put all of the original lines back
newtext.close()
确保您输入了文本文件的路径,但这个简短的脚本只会添加您想要的 line_count = Number 标题。干杯!
f.seek(0)
f.write("line_count = %s\n"%n)
f.close()
其中 n 是行计数值