1

I have the following code:

for filename in os.listdir('/home/ripperflo/Downloads/nightlight_geotiffs'):
    if filename.endswith('.tif'):           # take TIFF-files only
        with rasterio.open(os.path.join('/home/ripperflo/Downloads/nightlight_geotiffs', filename)) as f:           # open GeoTiff and store in f
            img = f.read()          # open GeoTiff as 3D numpy array
            matrix = img[0]         # 3D array to 2D array because nighlight images has only one band
            z_norm = stats.zscore(matrix)           # normalize 2D array

            # save to npy file
            np.save('/home/ripperflo/Downloads/nightlight_z-array/', filename, z_norm)

The Code is running so far. The only thing I need to know is: how can I save the numpy array as .npy file with the same name as the origin input file?

So the input file is called 'BJ2012_2.tif' and the output file should be called 'BJ2012_2.npy'. The process will later run in a loop. So each file from the folder will be normalized and saved with the same name but in a different file format in a different folder.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
frichter
  • 61
  • 6
  • 1
    I am not sure what exactly is your question. For starters you're calling `np.save` wrong. The first argument is the path and the second is the array. You are passing three arguments. Additionally, the [docs](https://numpy.org/doc/stable/reference/generated/numpy.save.html) say: *"If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one."*. What is the problem with your code? What is your current output and how it differs from your expected one? Are you getting errors? – Tomerikoo May 25 '21 at 21:20
  • Does this answer your question? [How to get the filename without the extension from a path in Python?](https://stackoverflow.com/q/678236/6045800) – Tomerikoo May 25 '21 at 21:28
  • Yes I know, I just wanted to make clear that each numpy file that is saved has the same name as its input file. And this is my question: How do I make my output file have the same name as my input file, except for the extension of course. It is a different format – frichter May 25 '21 at 21:38
  • Does this answer your question? [Changing file extension in Python](https://stackoverflow.com/q/2900035/6045800) Does this answer your question? [How to replace (or strip) an extension from a filename in Python?](https://stackoverflow.com/q/3548673/6045800) – Tomerikoo May 26 '21 at 14:27

2 Answers2

2

if you use pathlib.Path objects you could use Path.stem to get a filename minus the extension

>>> p = Path('/home/ripperflo/Downloads/nightlight_geotiffs/BJ2012_2.tif').stem
'BJ2012_2'

You can use the stem to write out to your target directory with the correct extension like so:

np.save(f"/home/ripperflo/Downloads/nightlight_z-array/{Path(filename).stem}.npy", z_norm)
will-hedges
  • 1,254
  • 1
  • 9
  • 18
  • 1
    "If file is a string or Path, a .npy extension __will be appended to the filename__ if it does not already have one." – Tomerikoo May 25 '21 at 21:36
  • @Tomerikoo the docs do say that, but I would say this is a good case of "explicit is better than implicit" – will-hedges May 26 '21 at 14:18
  • In that case, if you're using `pathlib`, wouldn't it be easier (and clearer) to just do `Path(filename).withsuffix('.npy')`? – Tomerikoo May 26 '21 at 14:24
  • @Tomerikoo I haven't personally used `with_suffix`, but since it does the same thing, sure. Seems like it would come down to personal preference, since it's creating an f-string either way. I find `{Path(filename).stem}.npy` to be easier to read, but I suppose `{Path(filename).with_suffix('.npy')}` might be considered *more* explicit. Either way, I'll have to try using `with_suffix` now that I know about it. – will-hedges May 26 '21 at 14:32
1

You can remove charachters from the end of a string using this syntax [:-3]

e.g.

tmp = "filename.tif"
print(tmp[:-3])

result

filename.

Similarly you can use it to get a string from the start, or from the end;

tmp = "filename.tif"
print(tmp[:3])
print(tmp[3:])

result

fil
tif

Updating your code to use "{}.npy".format(filename[:-4]) will replace tif with npy

# save to npy file
np.save("/home/ripperflo/Downloads/nightlight_z-array/{}.npy".format(filename[:-3]), z_norm)
Jay Hewitt
  • 1,116
  • 8
  • 16
  • If treating paths as strings, it is better to use [`str.removesuffix`](https://docs.python.org/3/library/stdtypes.html#str.removesuffix). And also note that "If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one." – Tomerikoo May 25 '21 at 22:49