Home > Back-end >  Generate output as list instead of multiple lines
Generate output as list instead of multiple lines

Time:07-13

I want to display the files and folders inside a directory in a specific format.

The folder looks like this:

/home/test_directory
    fg-2022-07-12
    fg-2022-07-11
    ag-2022-07-12

My code to display certain elements of the folder:

SRC = '/home/test_directory'

for root_dir_path, sub_dirs, files in os.walk(SRC):
    for folders in sub_dirs:
        if "fg-" in folders:
            print(folders)

Current output:

fg-2022-07-08
fg-2022-07-07

Desired output:

['fg-2022-07-08', 'fg-2022-07-07']

Preferably, I would like to generate the list instead of the multiple lines, but converting the multiple lines (current output) into a list would work too

CodePudding user response:

SRC = '/home/test_directory'

output = []
for root_dir_path, sub_dirs, files in os.walk(SRC):
    for folders in sub_dirs:
        if "fg-" in folders:
            output.append(folders)
print(output)

What you want is to output the list instead of the elements. A much smaller example would be:

l = ['a', 'b', 1]
for x in l:
    # when printing strings, quotes are omitted
    print(x)

This outputs:

a
b
1

Quote are not omitted when you print the list

print(l)

This prints:

['a', 'b', 1]
  • Related