如何在迭代文件路径字符串列表时获取索引和文件名?

时间:2018-01-06 19:14:57

标签: python list

假设我有一个列出一些csv文件的假设列表:

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

我希望印刷品像:

'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'

执行简单的for循环仅打印第一个字符串三次。我以为我会指定python的索引来“识别”我所指的文件,如下所示:

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')

然而,这也仅打印出第一个字符串。如何自定义每个索引的打印内容?

3 个答案:

答案 0 :(得分:3)

enumerate的作业:

for (idx, st) in enumerate(example_list, 1):
    print('This is file number {} for {}'.format(idx, st.split('/')[-1]))
  • enumerate(example_list, 1)枚举列表,并将起始索引设置为1

  • print('This is file number {} for {}'.format(idx, st.split('/')[-1]))以所需格式打印,st.split('/')[-1])获取/ split列表的最后一位成员。

由于/是POSIX系统中的目录分隔符,因此/不能包含split('/')[-1],因此os.path.basename应与os.path.basename相同。但是,使用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 BTW会更好。

示例:

RecyclerView

答案 1 :(得分:1)

os.path.basename您的列表,打印格式化的字符串。您可以使用>>> from os.path import basename >>> example_list = ['./Data/File_1.csv', ... './Data/File_2.csv', ... './Data/File_3.csv'] >>> >>> for i, fname in enumerate(example_list, 1): ... print('This is file number {} for file {}'.format(i, basename(fname))) ... This is file number 1 for file File_1.csv This is file number 2 for file File_2.csv This is file number 3 for file File_3.csv 获取文件的基本名称。

listaP prodotto = malloc(sizeof(prodotto));

答案 2 :(得分:1)

您需要enumerate (在迭代时获取索引)并使用os.path.basename (从文件路径获取文件名)来实现此目的。这里以列表理解表达式为例:

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

>>> ['This is file number {} for {}'.format(i, os.path.basename(name)) for i, name in enumerate(example_list)]
['This is file number 0 for File_1.csv', 'This is file number 1 for File_2.csv', 'This is file number 2 for File_3.csv']