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('\\', '/')
Related
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/ >>
I am writing a function and my input parameter is the file path: C:\Users\HP\Desktop\IBM\New folder
def read_folder(pth):
for fle in Path(pth).iterdir():
file_name = Path(pth) / fle
return file_name
For me to use this function, I need to specify r'' in the file path, ie.
read_folder(r'C:\Users\HP\Desktop\IBM\New folder')
Is there a way where I can avoid specifying r'' in the file path, ie. like the below and the code would work.
read_folder('C:\Users\HP\Desktop\IBM\New folder')
The reason why I want to do this is so to make it easier for the user to just copy and paste the directory path into the function and just run the function. So it's more for ease-of-use on the user end.
Many thanks.
You can't really do that because without prepending r to your string there's no way python interpreter would know that your string contains \ intentionally and not on purpose to escape the characters.
So you've to either use r"C:\Users\HP\Desktop\IBM\New folder" or "C:\\Users\\HP\\Desktop\\IBM\New folder" as argument while calling read_folder function.
You can escape the backslashes:
read_folder('C:\\Users\\HP\\Desktop\\IBM\New folder')
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
Following code :
def tema_get_file():
logdir='T:\\'
logfiles = sorted([ f for f in os.listdir(logdir) if f.startswith('tms_int_calls-')])
return logfiles[-1]
This runs fine, but I am trying to get logdir to run with a direct path :
\\servername\path\folder
The drive T is a mapped drive. Originally, the files are on the C Drive.
As soon as I do that, I get the error message :
WindowsError: [Error 3] The system cannot find the path specified:
'\servername\path\folder/.'
I've tried :
"\\servername\\path\\folder" , "\\servername\\path\\folder\\"
and
r"\\servername\path\folder" , r"\\servername\path\folder\"
and
"\\\\servername\\path\\folder" , "\\\\servername\\path\\folder\\"
For me both of the following work
os.listdir(r'\\server\folder')
os.listdir('\\\\server\\folder')
os.listdir(myUNCpath) cannot handle Windows UNC path correctly if the path string was not defined by a literal like myUNCpath = "\\\\servername\\dir1\\dir2" or using a raw string like myUNCpath = "\\servername\dir1\dir2 even if the string variable is defined like that because listdir always doubles backslash from string variable.
But what the heck one could do if getting the UNC path string by reading it from a ini file or by any other config file?
There is no way to edit as a literal, nor is it possible to make it a raw string using this r character in front of.
As a work around I found out that, it is possible to split an overall UNC path string variable into it's single components (to get rid off this dammned backslash characters) and to recompose it using a literal definition and by this setting the backslash characters again. Then the string works well - incredibel but true!
Here is my function, to perform this work around. The string which is given back from the function will work as expected if the path in the file is defined as
\servername\dir1\dir2 (without added backslash as a escape character)
...
myworkswellUNCPath = recomposeUNCpathstring(myUNCpath)
...
def recomposeUNCpathstring(UNCstring):
pathstring1 = UNCstring.replace("\\\\", "").strip()
pathComponents = pathstring1.split("\\")
pathstring = "\\\\" + pathComponents[0]
for i in range(1, len(pathComponents)-1):
pathstring = pathstring + "\\" + pathComponents[i]
return pathstring
Cheers
Stefan
I have a function in a python code whose argument is as follows:
save_geometry(r"""C:\Users\User0\Documents\test.txt """)
I want to modify the argument and be able to save to a different path with a different filename:
filename = "geometries.txt "
filepath = "D:/AllData/"
filefullpath = filepath + filename
Could someone help me how I should pass filefullpath to save_geometry? If there were no r in the argument of save_geometry, it would be easy. But I don't know how to deal with this r.
The r"" construct just tells Python that whatever's in the string should be interpreted as raw data.
"qw\n" == 'qw\n'
r"qw\n" == 'qw\\n'.
It's used because the "\" path separator is also used for newlines and such. You can skip it when putting in the argument; save_geometry(filefullpath) should do what you expect.
Note that the canonical way of putting together paths is os.path.join
path = os.path.join("D:\\", "AllData", "geometries.txt")
User3757614's answer addresses your concern of the raw string notation, but succinctly all the r"" notation does is tell Python that the following string should not treat \ as an escape character, but as a literal backslash. This is important since "C:\new folder" is actually
C:
ew folder
Since \n is a newline.
You cans use the os module to split your string into a folder path and file name.
e.g.
import os
pathname = os.path.dirname('C:\Users\User0\Documents\test.txt') #C:\Users\User0\Documents
filename = os.path.basename('C:\Users\User0\Documents\test.txt') #test.txt
Though you'll need to modify your path string because your \s will be interpreted and newline bytes