I've a .txt file with 790 lines. In those lines theres information that I want to keep and information that I want to get rid off. Follow a example of what it looks like.
InfoThatIWant:InfoThatIWant - InfoThatI**Don't**WantInfoThatI**Don't**WantInfoThatI**Don't**WantInfoThatI**Don't**Want BR1
InfoThatIWant:InfoThatIWant - InfoThatI**Don't**WantInfoThatI**Don't**WantInfoThatI**Don't**WantInfoThatI**Don't**WantInfoThatI**Don't**WantInfoThatI**Don't**Want BR1
Thats how the documento go on till the end. So, as you guys can see, every line have the info I want till the "-" and the info I don't want starts at the "-" and ends in the BR1, everytime. That probably is the logic that I need to follow in order to automatic erase this lines.
I'm new to coding and I'm having a hard time figuring out how to do that. Unfortunately I've no code example to index in here, but I'd aprecciate any information that u guys can give me.
CodePudding user response:
You can go simply by reading each line independantly, then splitting your line with '-' and getting only the first element as following:
info_to_keep = []
with open('my_file.txt', 'r ') as f:
lines = f.readlines()
for line in lines:
info_to_keep.append(line.split("-")[0]) # Getting your info
with open('my_file.txt', 'w ') as f: # Overwritting the file with only the info you want
for info in info_to_keep:
f.write(info "\n")
EDIT : Added how to re-write the file with only the info you want to keep
CodePudding user response:
f = open('file.txt', 'r ') f.truncate(0) # need '0' when using r