2

It must be easy but I still cant figure it out. Suppose I am reading lot of txt file with glob module.And do some processing, and later plotting them with matplotlib.

import glob
ascii = sorted(glob.glob('C:/Users/ENAMUL/PYTHON/*.txt')) 
for count,i in enumerate(ascii):
........
........

Now I want to save those figures. I can do it like this which will save them by counting numbers.

plt.savefig(str(count)+'png') 

But if I want to save them by taking their input file name, how can I do that? Any help please.

2 Answers 2

2

In the loop, i contains the name of the file, so:

import os.path

....

plt.savefig(os.path.splitext(os.path.basename(i))[0] + '.png')

It works like this. os.path.basename returns the filename:

In [2]: os.path.basename('foo/bar/baz.bat')
Out[2]: u'baz.bat'

Then splitext does the obvious:

In [3]: os.path.splitext(os.path.basename('foo/bar/baz.bat'))
Out[3]: (u'baz', u'.bat')

So:

In [4]: os.path.splitext(os.path.basename('foo/bar/baz.bat'))[0] + '.png'
Out[4]: u'baz.png'

If you want to keep the path, just remove the basename call, and only use splitext:

In [5]: os.path.splitext('foo/bar/baz.bat')[0] + '.png'
Out[5]: u'foo/bar/baz.png'
Sign up to request clarification or add additional context in comments.

2 Comments

what is the benefit of going this extra route, when the names are already stored in ascii?
@Schorsch The names in ascii still contain their path and extension.
0

You store the file name in ascii - so you should be able to use it when saving the figure:

plt.savefig(ascii[count] + '.png')

3 Comments

That would produce a filename with a double extension .txt.png. Probably not what was intended.
actually this line does my job. But I also understand the explanation on top. Right now it saves the figure in my input folder. If I create a folder for figure, how can I directed them to that folder?
if you want to redirect your output, I would suggest you use @RolandSmith answer - and put a new path before the file name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.