How to create a directory in Python inside a server?
Using the function mkdir it is possible to create a file in any directory within the computer folders:
Import os
diretorio = "C:\\Users\\CRIACAO 2\\Desktop\\teste"
os.mkdir(diretorio)
But when I try to create it inside the address of a server, the program is not able to find the indicated path:
Import os
diretorio = "\\servidor\ARABRINDES 1TB\Artes"
os.mkdir(diretorio)
FileNotFoundError: [WinError 3] the system cannot find the specified path: '\ server \ ARABRINDES 1TB\Artes\andrei '
How can I solve this problem?
2 answers
Your problem is that you are using only one counterbar, and paths to server start with two counterbar \\
...
Explaining better, Python interprets strings that have counterbars in a special way. For example, '\t'
is the tab, '\n'
is the line break, and '\\'
is a single bar!
You can see that this is the case through the error message:
FileNotFoundError: [WinError 3] O sistema não pode encontrar o caminho especificado:
'\servidor\ARABRINDES 1TB\Artes\andrei'
To solve, use four bars, i.e. two for each bar:
diretorio = "\\\\servidor\\ARABRINDES 1TB\\Artes"
Or better yet, use raw strings whenever you write a path:
diretorio = r"\\servidor\ARABRINDES 1TB\Artes"
Putting this r
before the string causes python to not process special characters inside it. It comes out exactly as it is written!
Read the documentation here: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
I had a similar problem, this error happened because it is executing the command for a relative path and not a absolute path. The correct would be to pass parameter all the way from the server.
Hope I helped.