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

2024-10-05 10:47:53 发布

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

我想在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在文件末尾被写入。为什么?在


顺便说一句,我试图简单化一些事情,只使用字符串,而不是文件。在

^{pr2}$

给予

'qwert123456789uiop'

“y”怎么了?在


Tags: 文件inreadifhereaswithopen
3条回答

不是Python的答案,但它可能会拓宽你的视野。使用sed

$ cat input.txt 
foo
bar
baz
INSERT HERE
qux
quux

$ sed '/INSERT HERE/anew stuff' < input.txt
foo
bar
baz
INSERT HERE
new stuff
qux
quux

命令a将在新行中追加文本。如果要在匹配项之前插入文本,请使用命令i

^{pr2}$

虽然文件的操作系统级别的详细信息有所不同,但通常,当您以r+模式打开一个文件并执行某些读或写操作时,“当前位置”将保留在最后一次读或写之后。在

当你这么做的时候:

fileContents = erroredFile.read()

erroredFile被读取到末尾,因此当前位置现在是“在末尾”。在

truncate函数默认使用当前位置作为截断的大小。假设文件的长度为100字节,因此当前位置“在末尾”是字节100。然后:

^{pr2}$

意思是“使文件的长度达到100字节”——它已经是。在

当前位置保留在文件末尾,因此后续的write将追加。在

假设您希望返回到文件的开头,和/或使用truncate(0)(请注意,truncate(0)将至少在类Unix的系统上,将seek位置保留在文件末尾,这样下一个{}会在原来的原始数据所在的位置留下一个洞)。您还可以稍微聪明一点:如果要插入,只需在适当的地方覆盖和扩展(根本不需要truncate)。在

(乔尔·辛兹已经回答了第二个问题,我明白了。)

如果你想写在文件中间使用

fileinput模块。在

import fileinput
for line in fileinput.input("C:\\Users\\Administrator\\Desktop\\new.txt",inplace=True):
    print "something", #print("something", end ="") for python 3

remember whatever you print that will go in the file.So you have to read and print every line and modify whichever you want to replace.Also use打印“asd”,...theat the end is important as It will prevent打印from putting a newline there.

相关问题 更多 >

    热门问题