This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 7 months ago.
How can I create a string that represents a Windows Path? I need to add a file that is generated dynamically to the end of the path as well. I have tried using raw strings but I can't seem to figure it out. Here's what I am trying to accomplish:
filename = "test.txt"
path = 'C:\Path\To\Folder\' + filename
Error I am seeing is: SyntaxError: EOL while scanning string literal
Sorry if this has been asked before I have tried looking at a few other SO questions and everyone reccomends using os.path.join but the problem there is I need to build a string, this code will not be running on a windows machine... Does that make a difference. Any help will be greatly appreciated!
You have a string literal, not a raw string. A raw string is a string literal with an r before it:
path = r'C:\Path\To\Folder\' + filename
Edit: Actually, that doesn't work because raw strings can't end with backslashes. If you still want to use a raw string, you could do one of the following:
path = r'C:\Path\To\Folder' + '\\' + filename
path = r'C:\Path\To\Folder\{}'.format(filename)
You could also double the backslashes:
path = 'C:\\Path\\To\\Folder\\' + filename
Yours didn't work because a backslash is a special character. For example, \n is not a backslash and an n; it is a new line. \' means to treat ' as a literal character instead of making it end the string. That means that the string does not end there, but you don't end it later in the line either. Therefore, when Python gets to the end of the line and you still haven't closed your string, it has an error. It is still better to use os.path.join(), though:
path = os.path.join(r'C:\Path\To\Folder', filename)
filename = "test.txt"
path = os.path.join(r'C:\Path\To\Folder',filename)
although really python works fine using / as a file separator on any OS
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 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('\\', '/')
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
This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 6 months ago.
So I have a script that needs to print to a file in a different directory. I give that absolute path and python doesn't like it.
Here's where the file is located:
C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt
(I know, long path, but QT plotter makes the file names really long)
I typed:
textfile = open('C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt', 'w')
And I get this error:
IOError: [Errno 22] invalid mode ('w') or filename:
I've read that I can use relative paths, but I am unsure how to give it a relative path with so many directories to go through.
Thanks!
The problem is that python is interpreting the backslashes in your path as escape sequences:
>>> 'C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
'C:\\Users\\Owner\\Documents\\Senior_design\\QT_Library\x08uild-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
Notice that both \b and \n get translated to something else. Use a "raw" string instead:
>>> r'C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
'C:\\Users\\Owner\\Documents\\Senior_design\\QT_Library\\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\\numbers.txt'
I believe this answer here may be of help.
Essentially, your backslashes are causing issues.