我想在 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 tofileinput.input()
or to theFileInput
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/