Python: change "\" to "\\" - python

I have an entry field that allows the user to enter their own directory/path structure when saving a file, if the user just copies their directory from windows explorer you can get text like "c:\directory\file.ext" how can I take text entered like that and replace it with the necessary "\" for the os module to use?

Use a raw string to get the backslashes
>>> path = r"c:\test\123"
>>> path
'c:\\test\\123'
>>> print path
c:\test\123

maybe os.path.normpath() would be helpful to you - and the documentation here

Related

Altering Windows file paths so that they use '/' instead of '\' [duplicate]

I am working in python and I need to convert this:
C:\folderA\folderB to C:/folderA/folderB
I have three approaches:
dir = s.replace('\\','/')
dir = os.path.normpath(s)
dir = os.path.normcase(s)
In each scenario the output has been
C:folderAfolderB
I'm not sure what I am doing wrong, any suggestions?
I recently found this and thought worth sharing:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath) # -> C:/temp/myFolder/example/
Your specific problem is the order and escaping of your replace arguments, should be
s.replace('\\', '/')
Then there's:
posixpath.join(*s.split('\\'))
Which on a *nix platform is equivalent to:
os.path.join(*s.split('\\'))
But don't rely on that on Windows because it will prefer the platform-specific separator. Also:
Note that on Windows, since there is a current directory for each
drive, os.path.join("c:", "foo") represents a path relative to the
current directory on drive C: (c:foo), not c:\foo.
Try
path = '/'.join(path.split('\\'))
Path names are formatted differently in Windows. the solution is simple, suppose you have a path string like this:
data_file = "/Users/username/Downloads/PMLSdata/series.csv"
simply you have to change it to this: (adding r front of the path)
data_file = r"/Users/username/Downloads/PMLSdata/series.csv"
The modifier r before the string tells Python that this is a raw string. In raw strings, the backslash is interpreted literally, not as an escape character.
Sorry for being late to the party, but I wonder no one has suggested the pathlib-library.
pathlib is a module for "Object-oriented filesystem paths"
To convert from windows-style (backslash)-paths to forward-slashes (as typically for Posix-Paths) you can do so in a very verbose (AND platform-independant) fashion with pathlib:
import pathlib
pathlib.PureWindowsPath(r"C:\folderA\folderB").as_posix()
>>> 'C:/folderA/folderB'
Be aware that the example uses the string-literal "r" (to avoid having "\" as escape-char)
In other cases the path should be quoted properly (with double backslashes) "C:\\folderA\\folderB"
To define the path's variable you have to add r initially, then add the replace statement .replace('\\', '/') at the end.
for example:
In>> path2 = r'C:\Users\User\Documents\Project\Em2Lph\'.replace('\\', '/')
In>> path2
Out>> 'C:/Users/User/Documents/Project/Em2Lph/'
This solution requires no additional libraries
How about :
import ntpath
import posixpath
.
.
.
dir = posixpath.join(*ntpath.split(s))
.
.
This can work also:
def slash_changer(directory):
if "\\" in directory:
return directory.replace(os.sep, '/')
else:
return directory
print(slash_changer(os.getcwd()))
this is the perfect solution put the letter 'r' before the string that you want to convert to avoid all special characters likes '\t' and '\f'...
like the example below:
str= r"\test\hhd"
print("windows path:",str.replace("\\","\\\\"))
print("Linux path:",str.replace("\\","/"))
result:
windows path: \\test\\hhd
Linux path: /test/hhd

Can't replace character "\"

I've been working on a program that reads out an specific PDF and converts the data to an Excel file. The program itself already works, but while trying to refine some aspects I ran into a problem. What happens is the modules I'm working with read directories with simple slashes dividing each folder, such as:
"C:/Users/UserX"
While windows directories are divided by backslashes, such as:
"C:\Users\UserX"
I thought using a simple replace would work just fine:
directory.replace("\" ,"/")
But whenever I try to run the program, the \ isn't identified as a string. Instead it pops up as orange in the IDE I'm working with (PyCharm). Is there anyway to remediate this? Or maybe another useful solution?
In general you should work with the os.path package here.
os.getcwd() gives you the current directory, you can add a subfolder of it via more arguments, and put the filename last.
import os
path_to_file = os.path.join(os.getcwd(), "childFolder", filename)
In Python, the '\' character is represented by '\\':
directory.replace("\\" ,"/")
Just try adding another backslash.
First of all you need to pass "C:\Users\UserX" as a raw string. Use
directory=r"C:\Users\UserX"
Secondly, suppress the backslash using a second backslash.
directory.replace("\\" ,"/")
All of this is required as in python the backslash (\) is a special character known as an escape character.
Try this:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath)
Output:<< C:/temp/myFolder/example/ >>

Replace \ with / With an Inputted Directory in Python

I am trying to replace an inputted paths' "\" with "/" to avoid a escaping character that messes with my code.
path = input("Enter the Directory: )
path.replace('\' , '/')
First off the reason I want to do this is because when the user inputs the path (copying and pasting it from Windows Explorer), it is in the C:\User\Folder convention which is giving me issues later on in my program when I have to output the real path and it gives me C:\User\Folder with double "\" because of the raw string method.
My path.replace() is not working because the '\' is thinking it is an escaping character. I also tried:
path.replace((r'\'), '/')
But the entire input turns into a string and does not work. Anyone have advice to do this, or another way to get an inputted path that is copied to have / instead of \? Thanks!
replace returns a copy of the string, you'll need to assign the result to the variable
path = input("Enter the Directory: ")
path = path.replace('\\' , '/')
Try using this:
path.replace('\\', '/')

How to convert back-slashes to forward-slashes?

I am working in python and I need to convert this:
C:\folderA\folderB to C:/folderA/folderB
I have three approaches:
dir = s.replace('\\','/')
dir = os.path.normpath(s)
dir = os.path.normcase(s)
In each scenario the output has been
C:folderAfolderB
I'm not sure what I am doing wrong, any suggestions?
I recently found this and thought worth sharing:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath) # -> C:/temp/myFolder/example/
Your specific problem is the order and escaping of your replace arguments, should be
s.replace('\\', '/')
Then there's:
posixpath.join(*s.split('\\'))
Which on a *nix platform is equivalent to:
os.path.join(*s.split('\\'))
But don't rely on that on Windows because it will prefer the platform-specific separator. Also:
Note that on Windows, since there is a current directory for each
drive, os.path.join("c:", "foo") represents a path relative to the
current directory on drive C: (c:foo), not c:\foo.
Try
path = '/'.join(path.split('\\'))
Path names are formatted differently in Windows. the solution is simple, suppose you have a path string like this:
data_file = "/Users/username/Downloads/PMLSdata/series.csv"
simply you have to change it to this: (adding r front of the path)
data_file = r"/Users/username/Downloads/PMLSdata/series.csv"
The modifier r before the string tells Python that this is a raw string. In raw strings, the backslash is interpreted literally, not as an escape character.
Sorry for being late to the party, but I wonder no one has suggested the pathlib-library.
pathlib is a module for "Object-oriented filesystem paths"
To convert from windows-style (backslash)-paths to forward-slashes (as typically for Posix-Paths) you can do so in a very verbose (AND platform-independant) fashion with pathlib:
import pathlib
pathlib.PureWindowsPath(r"C:\folderA\folderB").as_posix()
>>> 'C:/folderA/folderB'
Be aware that the example uses the string-literal "r" (to avoid having "\" as escape-char)
In other cases the path should be quoted properly (with double backslashes) "C:\\folderA\\folderB"
To define the path's variable you have to add r initially, then add the replace statement .replace('\\', '/') at the end.
for example:
In>> path2 = r'C:\Users\User\Documents\Project\Em2Lph\'.replace('\\', '/')
In>> path2
Out>> 'C:/Users/User/Documents/Project/Em2Lph/'
This solution requires no additional libraries
How about :
import ntpath
import posixpath
.
.
.
dir = posixpath.join(*ntpath.split(s))
.
.
This can work also:
def slash_changer(directory):
if "\\" in directory:
return directory.replace(os.sep, '/')
else:
return directory
print(slash_changer(os.getcwd()))
this is the perfect solution put the letter 'r' before the string that you want to convert to avoid all special characters likes '\t' and '\f'...
like the example below:
str= r"\test\hhd"
print("windows path:",str.replace("\\","\\\\"))
print("Linux path:",str.replace("\\","/"))
result:
windows path: \\test\\hhd
Linux path: /test/hhd

parse this directory path without losing slash

I have a wxPython application. I am taking in a directory path from a textbox using GetValue().
I notice that while trying to write this string to a variable:
"C:\Documents and Settings\tchan\Desktop\InputFile.xls",
python sees the string as
'C:\\Documents and Settings\tchan\\Desktop\\InputFile.xls' (missing a slash between "Settings" and "UserName).
More info:
The directory path string is created by the "open file" dialog, which creates a standard 'choose file' dialog you see in any 'open' function in a text processor. The string is written to a textbox and read later when the main thread begins (in case the user wants to change it).
EDIT: I realise that the problem comes from the '\t' being seen as a "tab" instead of normal forward slash. However I don't know how to work past this, since
I suspect there's a different way to get that path from wx that would avoid this issue, since it seems like this would be a fairly common problem. That said, there are a few ways to fix a mangled path like you describe, by converting the string you have to a raw string.
rawpath = "%r" % path
The resulting rawpath will likely be somewhat messy since it will probably add extra escapes to the backslashes and give you something like:
"'C:\\\\Documents and Settings\\tchan\\\\Desktop\\\\InputFile.xls'"
It seems like os.path.normpath will clean that up though.
import os.path
os.path.normpath(rawpath)
not saying this is the correct solution, but you can
x = "C:\tmp".encode('string-escape')
x
'C:\\tmp'
better, if you are using the file dialog
os.path.join(dlg.GetDirectory(),dlg.GetFilename())
where dlg is your dialog
You have to escape the slashes. \\ will store a literal \ in the string:
path = "C:\\Documents and Settings\\tchan\\Desktop\\InputFile.xls"

Categories

Resources