简体   繁体   中英

How to remove a line in a file with a specific string?

Let's say I have list.txt containing:

Apple
Orange
Banana
Watermelon

and I want to remove the line in the file that contains the string "Orange". I want the file to now look like this:

Apple
Banana
Watermelon

I do not want it to look like this:

Apple

Banana
Watermelon

I do not want to save it to a new file, I want it to be the same file. (all the examples I found were of 2 different files)

Any way to do this?

Through re.sub

>>> s = """Apple
Orange
Banana
Watermelon"""
>>> print(re.sub(r'.*?Orange.*\n', r'', s))
Apple
Banana
Watermelon

If the line contains orange at the middle or first or at the last in a file.

>>> s = """Apple
Orange
Banana
Watermelon
Orange"""
>>> print(re.sub(r'(?s)(?:[^\n]*?Orange[^\n]*\n|\n[^\n]*?Orange[^\n]*$)', r'', s))
Apple
Banana
Watermelon

Working with the file.

import re
with open('file.txt', 'r') as r:
    file = r.read()
    data = re.sub(r'(?s)(?:[^\n]*?Orange[^\n]*\n|\n[^\n]*?Orange[^\n]*$)', r'', file)

with open('file.txt', 'w') as f:
    f.write(data)

If you do a replace as you read the file, you can write the data back to the file:

filename = "data.txt"

with open (filename, "r") as myfile:
    data=myfile.read().replace('Orange\n', '')

with open (filename, "w") as myfile:
    myfile.write(data)

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