sam
sam

Reputation: 203

Find the directory that starts with a specific name using python?

I want to read a file that starts with the name VCALogParser_output_ARW.log, VCALogParser_output_CZC.log and so on. But In the same directory there is also files with the name VCALogParser_output_ARW_previous.log,VCALogParser_output_CZC_previous.log and so on. but I want to read only the files like VCALogParser_output_ARW.log. I tried doing like as below but it is reading both VCALogParser_output_ARW.log and VCALogParser_output_ARW_previous.log. can someone tell me how to do that ?

for dirpath, dirnames, filenames in os.walk(directory): 
    for filename in filenames:
        if filename.startswith('VCALogParser_output'): 

Upvotes: 1

Views: 1837

Answers (3)

Radek Kornik Wyka
Radek Kornik Wyka

Reputation: 50

Using endswith() should do the job:

for dirpath, dirnames, filenames in os.walk(directory): 
for filename in filenames:
    if (filename.startswith('VCALogParser_output') and (not filename.endswith('previous.log'))): 

Upvotes: 0

gsmafra
gsmafra

Reputation: 2494

It doesn't work because the files you're not interested also start with VCALogParser_output. You can add a term concerning the end of the file with the method endswith.

Try the following

for dirpath, dirnames, filenames in os.walk(directory): 
    for filename in filenames:
        if filename.startswith('VCALogParser_output'): 
            if not filename.endswith('_previous.log'): 

Upvotes: 0

Kenly
Kenly

Reputation: 26688

You can use re.match:

if re.match('VCALogParser_output_[A-Z]+\.log', filename):

Upvotes: 3

Related Questions