aquagremlin
aquagremlin

Reputation: 3549

how save a file in Python whose name has slashes in it

I am looping through a series of names in a tuple and I want to save the output during each loop using the tuple data as the filename. However the names have slashes in them.

layers = ['conv1/7x7_s2','pool1/3x3_s2']
for idx,layer in enumerate(layers):
    result=deepdream(net, img, end=layer)
    imag = PIL.Image.fromarray(result,'RGB')
    imag.save('files/'+str(layer)+'.png')

result contains a numpy array imag is the image layer is what i want the filename to be

However, the slash is being interpreted as a directory delimiter Is there any way to save the image as conv1/7x7_s2.png

or should I just convert the slash to a dash?

Upvotes: 7

Views: 11200

Answers (3)

eric
eric

Reputation: 1069

Yeah, there are some convoluted ways of keeping the "slash," but they probably aren't worth it (i.e. using a unicode division slash).

layers = ['conv1/7x7_s2','pool1/3x3_s2']
for idx, layer in enumerate(layers):
    print(layer.replace('/', '_'))
    # or maybe this might work?
    # print(layer.replace('/', u"\u2215"))

Upvotes: 5

Grismar
Grismar

Reputation: 31354

None of these characters can be used in filenames (at least not on a Windows file system): \, /, :, *, ?, ", <, > and |. They all have specific alternate meanings.

There is also no escape character or another way around it - you will simply need to omit or replace these characters in file names.

Upvotes: 4

Yugandhar Chaudhari
Yugandhar Chaudhari

Reputation: 3964

As the directory structure is defined you can't. As linux systems will parse the / as a component of the directory tree. You should simply change the slash to dash or underscores.

Upvotes: 0

Related Questions