如何在使用Python写入文件前将文件指针上移一行?

3 投票
2 回答
5708 浏览
提问于 2025-04-18 09:15

场景

有一个文件,最后面有两行空白行。当我往这个文件里添加内容时,它总是会在这两行空白行之后写入(这是肯定的)。

但是我只想要一行空白行,想把第二行空白行去掉。然后在第二行空白行的位置写入我添加的数据。

#-------Original file 
This is line 1 
This is line 2
[--blank line--] 
This is line 3
This is line 4
[--blank line--]
[--blank line--]

在上面的文件中添加“这是第5行”和“这是第6行”。

现在发生了什么!

#-------Original file 
This is line 1 
This is line 2
[--blank line--] 
This is line 3
This is line 4
[--blank line--] 
[--blank line--]  
This is line 5
This is line 6

我想要的结果!

#-------Original file 
This is line 1 
This is line 2
[--blank line--] 
This is line 3
This is line 4
[--blank line--]  #Only one blank line. Second blank line should be removed
This is line 5
This is line 6

我研究了一下,发现可以通过移动文件指针来解决这个问题。当我往文件里添加内容时,文件指针可能会停在第二行空白行之后。 如果我把文件指针向上移动一行,然后再添加“这是第5行”和“这是第6行”,这样可行吗?

如果可以的话,请告诉我该怎么做。 seek()函数似乎不是很有用!

除了seek()之外的任何想法也很受欢迎。

任何帮助都非常感谢。

2 个回答

2

这是根据特定情况的解决方案,只适用于 '\n' 的情况。

我想感谢 @otus。他的回答加上一些修改解决了我的问题。 :)

根据我的情况,我想开始添加新行时,文件指针默认是在文件的末尾。

#-------Original file 
This is line 1 
This is line 2
[--blank line--] 
This is line 3
This is line 4
[--blank line--]
[--blank line--]
* <-----------------------file pointer is here. 

假设 file1 是文件对象。我用 file1.tell() 来获取当前文件指针的位置。

在写入文件之前,我只做了这个:

 pos = file1.tell() #gives me current pointer
 pos =  pos - 1     #This will give above value, where second blank line resides
 file1.seek(pos)    #This will shift pointer to that place (one line up)

现在我可以继续写,比如 file1.write("这是第5行"),依此类推...

谢谢 otus 和 Janne(特别是关于缓冲的问题)..

3

这里有一个简单的方法,可以逐行读取文件,然后在倒数第二行之后把指针恢复到之前的位置。

with open('fname', 'rw') as f:
    prev = pos = 0
    while f.readline():
        prev, pos = pos, f.tell()
    f.seek(prev)
    # Use f

如果你不想花时间去逐行读取文件,你需要先决定支持哪些行结束符,而在这里,Python会为你处理这些问题。

撰写回答