Pregunta

I am using the code below to extract the file names from a directory and print them. However, the print is not easilly readable and I was wondering if anyone could help me think of a better way to display it by seperating it. So my question is how would you seperate this file name using python?

from os import listdir

def find_csv_filenames( path_to_dir, suffix=".csv" ):
    filenames = listdir(path_to_dir)
    return [ filename for filename in filenames if filename.endswith( suffix ) ]


filenames = find_csv_filenames('C:\Users\AClayton\Aug')
for name in filenames:
    print name

Which gives the filename Agusta_AW149_Ground_2011_7_29_14_50_0.csv.

I would like it to read something like Name=Augusta Test=Ground Date =29/7/2011. I would like to do this for many file names which have the same format/order, just the 'Test' so the 'Ground' will change and the Date.

Thanks for any help

¿Fue útil?

Solución

if you are sure that every filename will have that attribute order, you can use

name.split('_')

and just organize the new strings as you prefer. For instance, in your case you could do something like:

sep_names = name.split('_')
Name = 'Name='+sep_names[0]
Test = 'Test='+sep_names[2]
Data = 'Date='+sep_names[5]+'/'+sep_names[4]+'/'+sep_names[3]

Otros consejos

You could split the string using name.split('_'), which would return a list in the following format:

>>['Agusta', 'AW149', 'Ground', '2011', '7', '29', '14', '50', '0.csv']

Then you could print name.split('_')[0], which would give you Augusta, etc.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top