user3601754
user3601754

Reputation: 3862

Python - Glob without absolute path

I m using glob in order to get names of pairs of pictures for a great number of images. The only problem is that i get absolute path and i dont want of that, i need only names of pictures. How can i do?

import glob

A=sorted(glob.glob('/media/test/A*.png'))
B=sorted(glob.glob('/media/test/B*.png'))
NumbSeq=len(A)
for i in range(0,NumbSeq):
  print "\"%s\",\"%s\","%(A[i],B[i])

I get that :

 "/media/test/A170900_85495.460376.png","/media/test/B170900_85495.460376.png"

I need that :

 "A170900_85495.460376.png","B170900_85495.460376.png"

Upvotes: 10

Views: 24878

Answers (3)

Michael Currin
Michael Currin

Reputation: 680

Instead of glob(pathname), use the glob1(dirname, pattern) method to get the filenames.

>>> glob.glob1("some_dir", "*.png")
['foo.png', 'bar.png', ...]

>>> glob.glob("some_dir/*.png")
['/home/michael/A_dir/B_dir/some_dir/foo.png',
'/home/michael/A_dir/B_dir/some_dir/bar.png',
...]

Upvotes: 20

Eric Renouf
Eric Renouf

Reputation: 14520

Pass each name in A and B to os.path.basename before printing them:

for i in range(0,NumbSeq):
    print '"%s","%s"'%(os.path.basename(A[i]),os.path.basename(B[i]))

Upvotes: 1

user1846747
user1846747

Reputation:

Try this

os.path.basename(A[i])

this will return the filename alone.

import glob
import os

A=sorted(glob.glob('/media/test/A*.png'))
B=sorted(glob.glob('/media/test/B*.png'))
NumbSeq=len(A)

for i in range(0,NumbSeq):
  print '"%s","%s"'%(os.path.basename(A[i]),os.path.basename(B[i]))

This will give you

"A170900_85495.460376.png","B170900_85495.460376.png"

Upvotes: 2

Related Questions