Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to trim text from file and put it another file using python?

I have a text file called file1 like


    
        HelloWorldTestClass
        MyTestClass2
        MyTestClass4
        MyHelloWorld        
        ApexClass
    
    
        *
        ApexTrigger
    
    
        Book__c
        CustomObject
    
    56.0

Now i want to output my file as in file2 which contains test in the word and have output like this

        HelloWorldTestClass
        MyTestClass2
        MyTestClass4

I have a code like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import re
import os

file_contents1 = f'{os.getcwd()}/build/testlist.txt'
file2_path = f'{os.getcwd()}/build/optestlist.txt'
with open(file_contents1, 'r') as file1:
    
    file1_contents = file1.read()
   
# print(file1_contents)

# output = [file1_contents.strip() for line in file1_contents if "TestClass" in line]
# # Use a regudjlar expression pattern to match strings that contain "test"
test_strings = [x for x in file1_contents.split("\n") if re.search(r"test", x, re.IGNORECASE)]
# x = test_strings.strip("['t]")
# # Print the result
with open(file2_path, 'w') as file2:
    # write the contents of the first file to the second file
    for test in test_strings:
        file2.write(test)


But it is outputting
HelloWorldTestClass MyTestClass2 MyTestClass4

I didn’t find the related question if already asked please attached to it thanks

>Solution :

You can use the in operator with strings to check whether it contains your phrase:

with open('file1.txt', "r") as f_input:
    with open('file2.txt', "w") as f_output:
        for line in f_input:
            if "test" in line.lower():
                f_output.write(line)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading