在文件中写入行之后,如何在文件顶部写入行计数?

2024-05-16 18:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能告诉我,在使用python将行写入文件之后,如何在文件顶部写入行计数吗

line_count=?

sam
john
gus
heisenberg

Tags: 文件samcountlinejohn计数gusheisenberg
3条回答

给你

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()

确保您输入了文本文件的路径,但是这个简短的脚本只会固定在您想要的那一行\u count=Number头上。干杯

 f.seek(0)
 f.write("line_count = %s\n"%n)
 f.close()

其中n是行计数值

你不能这么简单地做。文件是一个字节序列。您必须首先确保在写入所有这些行时,将它们写入它们的最终位置。最简单的方法是在第一次写入文件时为行计数“保留”空间。正如您在描述中所做的那样,编写整个文件,但保留“占位符”空间用于行计数。例如,如果文件中最多有9999行,则为该计数保留四个字节:

line_count=????

sam
john
gus
heisenberg

完成所有行的写入后,使用seek(11)file.write()计数(格式为四个字符)返回到文件中相应的字节位置(字节11-14)

我假设您已经知道如何将行写入文件,以及如何格式化整数。您所缺少的只是基本逻辑和seek方法

相关问题 更多 >