0

Using python, I was trying to remove string content from input_file, so in my delete_list I was passing "*.sh".

what should have been passed to remove strings from file to my delete_list to remove string values from file.

test.py

#!/usr/bin/env python3
import sys

infile = "input_file"
outfile = "expected_file"

delete_list = ["*.sh"]
with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        for word in delete_list:
            line = line.replace(word, "")
        fout.write(line)

input_file

papaya.sh   10
Moosumbi.sh 44
jackfruit.sh 15
orange.sh 11
banana.sh 99
grapes.sh 21
dates.sh 6

expected_file

10
44
15
11
99
21
6
2
  • Is the problem really to remove a set of strings, or is the problem really just to "print the second column"? That's a much easier problem, and probably doesn't even need Python. Commented Jul 15, 2021 at 19:01
  • @TimRoberts printing second column will also work. But i was trying to eliminate string using python Commented Jul 15, 2021 at 19:06

2 Answers 2

1

Using regular expressions is probably the way to go. Here's an approach similar to what you wrote - we'll assume input.txt contains your input values, with output.txt as the export file:

#!/usr/bin/env python3
import re

infile = "input.txt"
outfile = "output.txt"
delete_list = [r'^.+\.sh\s*']

with open(infile) as fin, open(outfile, "w+") as fout:
    for line in fin:
        for word in delete_list:
            line = re.sub(word, "", line)
            fout.write(line)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use regular expressions

import re
from io import StringIO

pattern = re.compile(r'^.+\.sh\s*')

data = '''\
papaya.sh   10
Moosumbi.sh 44
jackfruit.sh 15
orange.sh 11
banana.sh 99
grapes.sh 21
dates.sh 6
'''

# replace these two with your open(...) calls
fin = StringIO(data)
fout = StringIO()

for line in fin:
    fout.write(pattern.sub('', line))

# just for demonstration
print(fout.getvalue())

2 Comments

i wont be knowing the content of string data. only i would be knowing the string content will ended with .sh
As mentioned in the comment in the code, you are supposed to replace, e.g., StringIO(data) with your open(infile). Surely you did not expect me to create a couple of files on my machine just for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.