2

I am a beginner in python. I am trying to read all of the ascii files from one folder and after converting them into Image, I want all of them to be saved into a different folder in same directory. The code is running but I am not getting any output and no error is displayed.

Code without loop, for single image is working perfectly.

Please help.

import os
import glob
import numpy as np
from PIL import Image

path = r'D:\user\ASCII'
outpath = 'D:\user\ASCII\TIFF'

filenames = glob.glob(path + "/*.asc") #read all files in the path mentioned

for x in filenames:
    myarray = np.loadtxt(x, skiprows=9)
    im = Image.fromarray(myarray)
    im.save(outpath + '/*.tif')

1 Answer 1

5

You have an asterisk in the save() function which makes no sense, it has nothing to match. It will not automatically substitute the * match from glob function. I think what you wanted to do something like this

src_fname, ext = os.path.splitext(x)  # split filename and extension
# construct output filename, basename to remove input directory
save_fname = os.path.join(outpath, os.path.basename(src_fname)+'.tif')
im.save(save_fname)

Remember to use os.path module functions instead of concatenating filenames with slashes as they handle edge cases correctly on every platform.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Ondřej for help. if we split the file name and extension then 'np.loadtext' would not work.
You split it after you use np.loadtxt(x), that way the original x variable is a full valid file name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.