3

设想

有一个文件,最后包含两个空行。当我将某些内容附加到文件时,它会在两个空行之后写入(这是肯定的)。

但我只想要一个空行并删除第二个空行。代替第二个空行,应写入附加数据。

#-------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() 之外的任何想法也值得赞赏。

非常感谢任何帮助。

4

2 回答 2

3

这是一种简单的方法,它逐行读取文件,然后将指针恢复到倒数第二个之后的状态:

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

如果您不想花时间阅读文件,您将需要决定例如支持哪些行尾,而 Python 会为您完成。

于 2014-06-10T09:01:07.040 回答
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("This is line 5") 等等......

感谢 otus 和 Janne(特别是缓冲区问题)..

于 2014-06-10T12:12:14.183 回答