I have a folder which contains n
csv
files, and they are all named event_1.csv
, event_2.csv
, all the way up to event_n.csv
.
I want to be able to raw_input
their folder path and then retrieve their names, file extension excluded.
I tried to do it but I only get printed the folder path as many times as there are csv
files in it. The filenames are never printed, instead, and they are what I want.
This is the best I have come up with so far, but it does the wrong thing:
import os
directoryPath=raw_input('Directory for csv files: ')
for i,file in enumerate(os.listdir(directoryPath)):
if file.endswith(".csv"):
print os.path.basename(directoryPath)
where directoryPath=C:\Users\MyName\Desktop\myfolder
, in which there are three files: event_1.csv
, event_2.csv
, event_3.csv
.
What I get is:
myfolder
myfolder
myfolder
What I want, instead, is:
event_1
event_2
event_3
PS: I expect to have as many as 100 files. Therefore I should be able to include situations like these, where the filename is longer:
event_10
event_100
EDIT
What can I add to make sure the files are read exactly in the same order as they are named? This means: first read event_1.csv
, then event_2.csv
, and so forth until I reach event_100.csv
. Thanks!
It seems like you are getting what you ask for. See this line in your code:
print os.path.basename(directoryPath)
It prints the directoryPath
.
I think it should be:
import os
directoryPath=raw_input('Directory for csv files: ')
for i,file in enumerate(os.listdir(directoryPath)):
if file.endswith(".csv"):
print os.path.basename(file)
Good luck!
EDIT:
Let's create a list of all file names without path and extension (l). Now:
for n in sorted(l, key=lambda x: int(x.split('_')[1])):
print n
Now you need to write your specific solution :)