0

I have a folder which contains numpy files. I need to create a numpy list where I will put all my numpy file names. For that, I use this code:

import os

a = open('C:\\Users\\user\\My_Test_Traces\\Traces.list_npy', "w")
for path, subdirs, files in os.walk(r'C:\\Users\\user\\CPA_test_1000_Tests\\test'):
   for filename in files:
      f = os.path.join(path, filename)
      a.write(str(f) + os.linesep)  

As a result, it gives me a list of my files and their paths like this:

   C:\\Users\\user\\My_Test_Traces\\ Trace1_Pltx1

   C:\\Users\\user\\My_Test_Traces\\ Trace2_Pltx2

   C:\\Users\\user\\My_Test_Traces\\ Trace3_Pltx3

   C:\\Users\\user\\My_Test_Traces\\ Trace4_Pltx4

however , I need only the files name, I don't need any spaces between lines:

   Trace1_Pltx1
   Trace2_Pltx2
   Trace3_Pltx3
   Trace4_Pltx4
  • then why are you joining with the `path`? The `filename` must be what you want to have. – Ma0 Mar 20 '17 at 10:55

3 Answers3

0

There is a function tyhat is doing exactly what you need, you should try this:

os.path.basename(path)
rakwaht
  • 3,666
  • 3
  • 28
  • 45
0

You can use,

from os.path import basename
print basename('path/file.txt')

If you don't want extension, refer the post

Community
  • 1
  • 1
chakku
  • 57
  • 1
  • 12
  • it gives me an empty list, I need the name of my files in the list without the path –  Mar 20 '17 at 11:06
0

Maybe this is better:

import os

folder = 'C:\\Users\\user\\CPA_test_1000_Tests\\test'

with open('C:\\Users\\user\\My_Test_Traces\\Traces.list_npy', 'w') as fp:
    fp.write(os.linesep.join(os.listdir(folder)))
Ke Li
  • 942
  • 6
  • 12