简体   繁体   English

覆盖python文件中的一些数据

[英]overwrite some data in a python file

I was hoping someone could help me, I am currently trying to add some data into a text file, however the way I am doing it isnt giving me what I want. 我希望有人可以帮助我,我目前正在尝试将一些数据添加到文本文件中,但是我这样做的方式并没有给我想要的东西。 I Have a file with 20+ lines in it with text and want to overwrite the first 30 characters of the file with 30 new characters. 我有一个包含20多个行的文本文件,并想用30个新字符覆盖文件的前30个字符。 The code I have deletes all the content and adds the 30 characters only. 我拥有的代码删除所有内容,并仅添加30个字符。 Please help :) 请帮忙 :)

file=open("text.txt", "w")

is there something wrong with this to why its reoving all of the original data too instead of simply overwriting over it? 这有什么问题为什么为什么它也显示所有原始数据而不是简单地覆盖它呢?

One way is to read the whole file into a single string, create a new string with first 30 characters replaced and rewrite the whole file. 一种方法是将整个文件读取为单个字符串,创建一个替换为前30个字符的新字符串,然后重写整个文件。 This can be done like this: 可以这样完成:

with open("text.txt", "r") as f:
    data = f.read()

new_thirty_characters = '<put your data here>'

new_data = new_thirty_characters + data[30:]

with open("text.txt", "w") as f:
    f.write(new_data)

Ideally, you have to check that file contains more than 30 characters after it's read. 理想情况下,读取文件后,必须检查文件是否包含30个以上的字符。 Also, do not use file and other reserved names as variable names. 另外,请勿将文件名和其他保留名用作变量名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM