Hi
I have read articles related converting backward to forward slashes.
But sol was to use raw string.
But Problem in my case is :
I will get file path dynamically to a variable
var='C:\dummy_folder\a.txt'
In this case i need to convert it to Forward slashes.
But due to '\a',i am not able to convert to forward slashes
How to i convert it? OR How should i change this string to raw string so that i can change it to forward slash
Don't do this. Just use os.path and let it handle everything. You should not explicitly set the forward or backward slashes.
>>> var=r'C:\dummy_folder\a.txt'
>>> var.replace('\\', '/')
'C:/dummy_folder/a.txt'
But again, don't. Just use os.path and be happy!
There is also os.path.normpath(), which converts backslashes and slashes depending on the local OS. Please see here for detailed usage info. You would use it this way:
>>> string = r'C:/dummy_folder/a.txt'
>>> os.path.normpath(string)
'C:\dummy_folder\a.txt'
Handling paths as a mere string could put you into troubles.; even more if the path you are handling is an user input or may vary in unpredictable ways.
Different OS have different way to express the path of a given file, and every modern programming language has own methods to handle paths and file system references. Surely Python and Ruby have it:
Python: os.path
Ruby: File and FileUtils
If you really need to handle strings:
Python: string.replace
Ruby : string.gsub
Raw strings are for string literals (written directly in the source file), which doesn't seem to be the case here. In any case, forward slashes are not special characters -- they can be embedded in a regular string without problems. It's backslashes that normally have other meaning in a string, and need to be "escaped" so that they get interpreted as literal backslashes.
To replace backslashes with forward slashes:
# Python:
string = r'C:\dummy_folder\a.txt'
string = string.replace('\\', '/')
# Ruby:
string = 'C:\\dummy_folder\\a.txt'
string = string.gsub('\\', '/')
>>> 'C:\\dummy_folder\\a.txt'.replace('\\', '/')
'C:/dummy_folder/a.txt'
In a string literal, you need to escape the \ character.
Related
I am using replace string method in Python and I am finding something that I cannot understand.
Changing the way that a folder is written in python to windows notation, I find that replace method will change this double / for a double \ instead of just one \ as intended.
folder_im_wdows = folder_im_wdows.replace("//","\\")
But the most impressive, is that when I try a workaround doing the next
folder_im_wdows = folder_im_wdows.replace("//",chr(92))
Python does the same...
The original variable is: //xxxxx//xxxx//xxxx//xxxx//xxx//xxxxx
And I want to get -> \xxx\x\x\x
What's happening with replace method?
This is because python's CLI escapes backslashes.
Example from python's CLI:
>>> str = "abc//def//fgh"
>>> str.replace("//", "\\")
'abc\\def\\fgh'
>>> print(str.replace("//", "\\"))
abc\def\fgh
>>>
Also, you should need to use \\ and not only \, because you need to escape the backslash character, well, I do.
Use os.path for working with path names:
import os
os.path.normpath('C:/Users/Bob/My Documents')
os.path.abspath would do the job too (it uses os.path.normpath)
Note: requires host to be windows, if that's not the case you can use ntpath.normpath directly
https://docs.python.org/library/os.path.html#os.path.normpath
Avoid regexes, replaces and all that. You're going to get it wrong in some subtle way.
This is a code for accessing a file inside a folder using with open() as:{} option.
with open("DATABASE\password.txt") as _2_:
password=_2_.readlines()
with open("DATABASE/names.txt") as _3_:
names=_3_.readlines()
with open("DATABASE\email.txt") as _4_:
email=_4_.readlines()
In this code, if I put "DATABASE\names.txt", as I did for password and email; instead of "DATABASE/names.txt"; it does not work. Please Tell me the reason for the same.
You need to add another backslash. Example: open("path\\to\\file.txt")
Your errors are happening because you need to escape the backslash by adding another one. Such a thing won't happen with /.
You need to escape the \, use raw string r or forward slashes as you have already tried:
"DATABASE\\names.txt" # double \
r"DATABASE\names.txt" # raw string
"DATABASE/names.txt" # use forward slashes
\n is a newline character.
In [7]: print "DATABASE\names.txt" # interpreted as two lines
DATABASE
ames.txt
In [8]: print r"DATABASE\names.txt"
DATABASE\names.txt
A backslash has a special meaning in python, it is used to escape characters.
When I'm using Python 3 to launch a program via subprocess.call(), why do I need 4 backslashes in paths?
This is my code:
cmd = 'C:\\\\Windows\\\\System32\\\\cmd.exe'
cmd = shlex.split(cmd)
subprocess.call(cmd)
When I examine the command line of the launched cmd.exe instance with Task Manager, it shows the path correctly with only one backslash separating each path.
Because of this, I need this on Windows to make the paths work:
if platform.platform().startswith('Windows'):
cmd = cmd.replace(os.sep, os.sep + os.sep)
is there a more elegant solution?
Part of the problem is that you're using shlex, which implements escaping rules used by Unix-ish shells. But you're running on Windows, whose command shells use different rules. That accounts for one level of needing to double backslashes (i.e., to worm around something shlex does that you didn't need to begin with).
That you're using a regular string instead of a raw string (r"...") accounts for the other level of needing to double backslashes, and 2*2 = 4. QED ;-)
This works fine on Windows:
cmd = subprocess.call(r"C:\Windows\System32\cmd.exe")
By the way, read the docs for subprocess.Popen() carefully: the Windows CreateProcess() API call requires a string for an argument. When you pass a sequence instead, Python tries to turn that sequence into a string, via rules explained in the docs. When feasible, it's better - on Windows - to pass the string you want directly.
When you are creating the string, you need to double each backslash for escaping, and then when the string is passed to your shell, you need to double each backslash again. You can cute the backslashes in half by using a raw string:
cmd = r'C:\\Windows\\System32\\cmd.exe'
\ has special meaning - you're using it as part of an escape sequence. Double up the backslashes, and you have a literal backslash \.
The caveat is that, with only one pair of escaped backslashes, you still have only one literal backslash. You need to escape that backslash, too.
Alternatively, why not just use os.sep instead? You'll be able to ensure your code is more portable (since it'll use the system-specific separator), and you won't have to deal [directly] with escaping backslashes.
As John points out 4 slashes isn't necessary when accessing files locally.
One place where 4 slashes is necessary is when connecting to (generally windows) servers over SMB or CIFS.
Normally you would just use \servername\share\
But each one of those slashes needs to be escaped. So thus the 4 slashes before servernames.
you could also use subprocess.call()
import subprocess as sp
sp.call(['c:\\program files\\<path>'])
I have two strings:
C:\Data
and another folder
Foo1
I need, the windows output to be
C:\Data\Foo1
and the Linux output to be
/data/foo1
assuming /data is in linux. Is there any constant separator that can be used in Python, that makes it easy to use irrespective of underlying OS?
Yes, python provides os.sep, which is that character, but for your purpose, the function os.path.join() is what you are looking for.
>>> os.path.join("data", "foo1")
"data/foo1"
os.path.normpath() will normalize a path correctly for Linux and Windows. FYI, Windows OS calls can use either slash, but should be displayed to the user normalized.
The os.path.join() is always better. As Mark Tolonen wrote (my +1 to him), you can use a normal slash also for Windows, and you should prefer this way if you have to write the path explicitly. You should avoid using the backslash for paths in Python at all. Or you would have to double them in strings or you would have to use r'raw strings' to suppress the backslash interpretation. Otherwise, 'c:\for\a_path\like\this' actually contains \f, \a, and \t escape sequences that you may not notice in the time of writing... and they may be source of headaches in future.
I have the following string read from an XML elememnt, and it is assigned to a variable called filename. I don't know how to make this any clearer as saying filename = the following string, without leading someone to think that I have a string literal then.
\\server\data\uploads\0224.1307.Varallo.mov
when I try and pass this to
os.path.basename(filename)
I get the following
\\server\\data\\uploads\x124.1307.Varallo.mov
I tried filename.replace('\\','\\\\') but that doesn't work either. os.path.basename(filename) then returns the following.
\\\\server\\data\\uploads\\0224.1307.Varallo.mov
Notice that the \0 is now not being converted to \x but now it doesn't process the string at all.
what can I do to my filename variable to get this String in a proper state so that os.path.basename() will actually give me back the basename. I am on OSX so the uncpath stuff is not available.
All attempts to replace the \ with \\ manually fail because of the \0 getting converted to \x in the beginning of the basename.
NOTE: this is NOT a string literal so r'' doesn't work.
We need more information. What exactly is in the variable filename? To answer, use print repr(filename) and add the results to your question above.
Wild guess
DISCLAIMER: This is a guess - try:
import ntpath
print ntpath.basename(filename)
All the downvoting in the world won't change the fact that you're doing it wrong. os.path is for native paths. \\foo\bar\baz is not a OS X path, it's a Windows UNC. posixpath is not equipped to handle UNCs; ntpath is.