Code for different file type in a directory | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Code for different file type in a directory

How to write a code which will read a directory having both csv and psv file and do split separately

15th Feb 2017, 2:22 PM
Dinesh Das
Dinesh Das - avatar
6 Réponses
+ 5
import os dir = os.listdir() csv = [ ] psv = [ ] for f in dir: ext = os.path.splitext(f)[1].lower() if ext == 'csv': csv.append(f) elif ext == 'psv': psv.append(f) print(csv) print(psv)
15th Feb 2017, 4:22 PM
visph
visph - avatar
+ 2
You may want to use os.listdir () to get a full list of files and use 'if' to see if a file is csv or psv.
15th Feb 2017, 3:48 PM
Sungmin Woo
Sungmin Woo - avatar
+ 2
You have already two lists of filenames, which can be used / formated as you want ^^ I raw print the two arrays just to log purpose ;) Maybe you want not split the lists, but join it in a string? 'Split' is for cuting a string as items of a list, contrarly: str1 = '\n'.join(csv) str2 = '|'.join(psv) print(str1) print(str2) str1 = str1.split('\n') str2 = str2.split('|') print(str1) print(str2)
15th Feb 2017, 4:42 PM
visph
visph - avatar
+ 1
Yes, you must have to loop inside the files lists, opening each, reading content and split it according to the delimiter used in your csv files to get theur content in a list...
15th Feb 2017, 6:29 PM
visph
visph - avatar
0
@visph I think i need to write split by pipe or comma separately or the above will work?
15th Feb 2017, 4:30 PM
Dinesh Das
Dinesh Das - avatar
0
I have to do different operations on each field of a csv file and different for psv. More of all i was looking for a config kind of function which will take the file and split them according to their delimiters. And saved in a different DF
15th Feb 2017, 4:59 PM
Dinesh Das
Dinesh Das - avatar