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
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
CodePudding user response:
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)