文件'webiste.txt‘包含文本:
welcome to geeksforgeeksPython代码:
f = open('website.txt', 'a')
f.seek(11)
f.write("Python")
f.close()需要的输出:welcome to python geeksforgeeks
实际输出:welcome to geeksforgeekspython
当我在'a‘模式下运行这段代码时,数据会追加到最后一个位置,而不是第11个位置。在'w‘模式下,数据在第11位输入,但其余数据被覆盖。
我们如何才能在不覆盖的情况下添加第11索引的python?
发布于 2021-08-02 10:54:58
首先使用'r‘方法打开以读取内容,然后使用'w’重写内容,下面的代码可能会有所帮助:)
with open('website.txt','r') as f:
content = f.read()
with open('website.txt','w') as f:
f.write(content[:11] + "Python" + content[11:])https://stackoverflow.com/questions/68620266
复制相似问题