Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index and filename while iterating the list of file path string?

Tags:

python

list

Say I have a hypothetical list that lists down some csv files:

example_list = ['./Data/File_1.csv',
                './Data/File_2.csv',
                './Data/File_3.csv']

And I would like the print to be like:

'This is file number 1 for File_1.csv'
'This is file number 2 for File_2.csv'
'This is file number 3 for File_3.csv'

Doing a simple for loop prints only the first string three times. I thought I would specify the indexes for python to 'recognise' which file I'm referring to, like so:

for data in example_list:
    if data[0]:
        print('This is file number 1 for File_1.csv')
    elif data[1]:
        print('This is file number 2 for File_2.csv')
    else:
        print('This is file number 3 for File_3.csv')

This too however prints out only the first string. How do I customise what is printed for each index?

like image 630
shiv_90 Avatar asked Dec 02 '25 20:12

shiv_90


1 Answers

Job for enumerate:

for (idx, st) in enumerate(example_list, 1):
    print('This is file number {} for {}'.format(idx, st.split('/')[-1]))
  • enumerate(example_list, 1) enumerates the list with setting starting index as 1

  • print('This is file number {} for {}'.format(idx, st.split('/')[-1])) prints in desired format, with st.split('/')[-1]) getting the last member of the / split-ted list.

As / is the directory separator in POSIX systems, no filename can contain /, so split('/')[-1] should works the same as os.path.basename. But, it's better to use os.path.basename BTW.

Example:

In [46]: example_list = ['./Data/File_1.csv',
                './Data/File_2.csv',
                './Data/File_3.csv']

In [47]: for (idx, st) in enumerate(example_list, 1):
    print('This is file number {} for {}'.format(idx, st.split('/')[-1]))
   ....:     
This is file number 1 for File_1.csv
This is file number 2 for File_2.csv
This is file number 3 for File_3.csv
like image 197
heemayl Avatar answered Dec 05 '25 10:12

heemayl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!