I have a problem with this script. In the output it doubles \\
.
import os
import time
import shutil
login = os.getlogin()
print(login)
while True:
filepath = input()
if filepath == 'end':
break
elif filepath[0:4] == 'copy': #im start command with 'copy' to copy file like 'copy C:\\Users...'
dirlist = os.listdir(filepath[5::])
print('Type dir to copied file')
codir = input('copy dir is..\n')
shutil.copy(filepath[5::], codir)
elif filepath[0:6] == 'search': #im start command with 'search' to copy file like 'search C:\\Users...'
print(filepath[6:-1])
dirlist = os.listdir(filepath[6::])
searchfile = input('file you want to search\n')
if searchfile in dirlist:
print("True")
else:
dirlist = os.listdir(filepath) # if it has no command, it's just show dir list
print(dirlist)
print('Script end!')
Output:
$ Tester.py
Artem
С:\\\Users
Traceback (most recent call last):
File "C:\Users\Artem\Desktop\Tester.py", line 24, in <module>
FileNotFoundError: [WinError 3] Системе не удается найти указанный путь: 'С:\\\\Users'
^System can't reach this way:'C:\\\\Users'
Why does it double \\
?
CodePudding user response:
Long ago, Microsoft chose to use the backslash \
as a separator, perhaps through naivete (though it seems like an intentional choice to thwart compatibility), while it's been an escape character for an eternity (indicating a special character like \n
for a newline or \t
for a tab) and the rest of the sane world uses /
for this amongst many reasons.
\\
is displaying an escaped backslash \
for compatibility
The system has trouble displaying this, but you can use /
and it'll work fine in most, if not all, cases
You may also find pathlib does everything you need for all your pathing more nicely than pure string handling!