我想在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”怎么了?在
不是Python的答案,但它可能会拓宽你的视野。使用
sed
:命令
^{pr2}$a
将在新行中追加文本。如果要在匹配项之前插入文本,请使用命令i
:虽然文件的操作系统级别的详细信息有所不同,但通常,当您以
r+
模式打开一个文件并执行某些读或写操作时,“当前位置”将保留在最后一次读或写之后。在当你这么做的时候:
流
erroredFile
被读取到末尾,因此当前位置现在是“在末尾”。在truncate函数默认使用当前位置作为截断的大小。假设文件的长度为100字节,因此当前位置“在末尾”是字节100。然后:
^{pr2}$意思是“使文件的长度达到100字节”——它已经是。在
当前位置保留在文件末尾,因此后续的
write
将追加。在假设您希望返回到文件的开头,和/或使用}会在原来的原始数据所在的位置留下一个洞)。您还可以稍微聪明一点:如果要插入,只需在适当的地方覆盖和扩展(根本不需要
truncate(0)
(请注意,truncate(0)
将至少在类Unix的系统上,将seek位置保留在文件末尾,这样下一个{truncate
)。在(乔尔·辛兹已经回答了第二个问题,我明白了。)
如果你想写在文件中间使用
fileinput
模块。在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”,...the
,at the end is important as It will prevent
打印from putting a newline there.
相关问题 更多 >
编程相关推荐