python - 在 Python 中的文本文件中间插入一行

标签 python python-3.x

我想在 Python 中的文本文件中间插入一行,所以我尝试了

with open(erroredFilepath, 'r+t') as erroredFile:
    fileContents = erroredFile.read()

    if 'insert_here' in fileContents:
        insertString.join(fileContents.rsplit('insert_here'))
        erroredFile.truncate()
        erroredFile.write(insertString)

但是,insertString 被写在文件的末尾。为什么?


顺便说一句,我尝试通过仅使用字符串而不是文件来简化事情。

'123456789'.join('qwertyuiop'.split('y'))

给予

'qwert123456789uiop'

'y' 怎么了?

最佳答案

如果你想写在文件中间使用fileinput模块。

import fileinput
for line in fileinput.input(erroredFilepath, inplace=True):
    print("something", end ="")

来自 docs

if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently).

无论您打印 什么,都将放入文件中。因此,您必须阅读并打印 每一行,然后修改您想要替换的内容。此外,当 print 现有行时,请使用 end="",因为它会阻止 print 添加额外的换行符。

关于python - 在 Python 中的文本文件中间插入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28538146/

相关文章:

python - 计算分布的置信水平

python - 当您拥有的只是一个可调用对象时,有没有一种方法可以访问方法的类

python - 如何修复在 Flask-uwsgi-Nginx 设置中被 Post 请求延迟的 websocket 消息?

python - 为什么 Datetime 的 `.timestamp()` 方法返回 `OSError: [Errno 22] Invalid argument` ?

python - 将 X、Y、Z 值转换为矩阵图

javascript - 如何根据具有不同前缀的其他字符串重命名字符串?

python - 如何在 Python 中比较两个 SQLite 数据集并搜索相似之处?

python - 不识别 Python 中的循环变量

python - 调试 urwid 应用程序的好选择是什么?

用于 sql 插入的 Python 代码优化