python - 如何在使用python写入文件之前将文件指针排成一行?

标签 python file file-pointer

Scenario

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

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

#-------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”。

What is happening right now!

#-------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

What I want !

#-------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() 之外的任何想法也很受欢迎。

非常感谢任何帮助。

最佳答案

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

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

如果您不想花时间通读文件,您需要做出决定,例如支持什么行尾,而这里 Python 会为你做这件事。

关于python - 如何在使用python写入文件之前将文件指针排成一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136425/

相关文章:

python 3 : Formatting a string with multiple same keywords but unique strings to replace them

vb.net - 如何在vb.net中读取excel文件后释放它

C++ : getline() function does not include last character/string when reading from a file

c - 什么是文件指针模式?

c++ - 前进文件指针以跳过文件中的数字

python - 将 gRPC 错误代码映射到 HTTP 错误代码

python - 如何创建一个在复选框右侧显示复选框标签的 Django 表单?

python - 使用 shell 脚本 Ubuntu 遍历目录中的文件

c++ - 使用 int 作为模式在 C++ 中打开文件

c - Fopen 无法从命令行读取