简体   繁体   中英

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. The code I have deletes all the content and adds the 30 characters only. 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. 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. Also, do not use file and other reserved names as variable names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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