Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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?

like image 278
aquagremlin Avatar asked Mar 28 '19 05:03

aquagremlin


People also ask

How do you handle a slash in Python?

Use two backslashes to represent a backslash Use the syntax "\\" within the string literal to represent a single backslash.

Can file names contain slashes?

The short answer is: No, you can't. It's a necessary prohibition because of how the directory structure is defined. And, as mentioned, you can display a unicode character that "looks like" a slash, but that's as far as you get.

What does 2 slashes do in Python?

In Python, you use the double slash // operator to perform floor division. This // operator divides the first number by the second number and rounds the result down to the nearest integer (or whole number).


2 Answers

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"))
like image 195
eric Avatar answered Oct 31 '22 21:10

eric


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.

like image 41
Grismar Avatar answered Oct 31 '22 21:10

Grismar