Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I have a directory with 100s of files in the following format.

 summary-0000016b9bf45ec8-AAAACCCC0286.json

 summary-0000016b9bf47180-AAAACCCC0286.json

 summary-0000016b9bf47746-AAAACCCC0286.json

 summary-0000016b9bf47cd8-AAAACCCC0286.json

 summary-0000016b9bf47f48-AAAACCCC0286.json

 summary-0000016b9bf4818e-AAAACCCC0286.json

I need to extract the field after the summary and create a list of it. I am using an empty list and trying to append my output to it. Below is the code to create an empty list and append the fields I am extracting to it.

for files in dir:

  if 'summary' in files and len(files.split('-')) > 1:

    s_addr = []

    s_addr.append(files.split('-')[1])

    print (s_addr)

The output I am getting is a list for each item extracted as shown below:

['0000016b9bf31d5e']

['0000016b9bf45ec8']

['0000016b9bf1d8c4']

['0000016b9bf3c920']

['0000016b9bf2371f']

['0000016b9bf3d8ec']

['0000016b9bf11cb6']

Expected output is :

['0000016b9bf31d5e','0000016b9bf45ec8','0000016b9bf1d8c4','0000016b9bf3c920','0000016b9bf2371f','0000016b9bf3d8ec','0000016b9bf11cb6']

What am i doing wrong?

1 Answer

0 votes
by (25.1k points)

This issue is occurring because on line 3 you are assigning an empty list to s_addr. So for each loop s_addr gets rewritten. You need to put line 3 outside the for loop. e.g.:

s_addr = []

for files in dir:

  if 'summary' in files and len(files.split('-')) > 1:

    s_addr.append(files.split('-')[1])

    print (s_addr)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jan 14, 2020 in Python by Rajesh Malhotra (19.9k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...