我想写到文件的一行中间。
例如,我有一个文件:Text.txt:
"i would like to insert information over here >>>>>>>[]<<<<<<<<"
是否有可能精确索引在哪里:file.write()
必须开始写?
我从这个开始:
file = open(file_path, 'w')
file.write()
我认为你可以做的是用你想要的相同数量的其他字符替换已经存在的字符。您可以打开一个文件,找到起始点,然后开始写入。但是如果您使用f.write()
,您将覆盖下面的所有字节。如果你想"插入"介于两者之间,您必须读取并重写文件的所有以下内容。
覆盖:
with open('text.txt', 'w') as f:
f.write("0123456789")
# now the file 'text.txt' has "0123456789"
with open('text.txt', 'r+b') as f:
f.seek(-4, 2)
f.write(b'a')
# now the file 'text.txt' has "012345a789"
插入:
with open('text.txt', 'w') as f:
f.write("0123456789")
# now the file 'text.txt' has "0123456789"
with open('text.txt', 'r+b') as f:
f.seek(-4, 2)
the_rest = f.read()
f.seek(-4, 2)
f.write(b'a')
f.write(the_rest)
# now the file 'text.txt' has "012345a6789"
import fileinput
file = [The file where the code is]
for line in fileinput.FileInput(file, inplace=1):
if [The text that should be in that line] in line:
line = line.rstrip()
line = line.replace(line, [The text that should be there after this file was run])
print (line,end="")
作为该行中的文本,您应该输入整行,否则它无法工作(我没有测试过)