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
Related
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 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('\\', '/')
I have to build the full path together in python. I tried this:
filename= "myfile.odt"
subprocess.call(['C:\Program Files (x86)\LibreOffice 5\program\soffice.exe',
'--headless',
'--convert-to',
'pdf', '--outdir',
r'C:\Users\A\Desktop\Repo\',
r'C:\Users\A\Desktop\Repo\'+filename])
But I get this error
SyntaxError: EOL while scanning string literal.
Try:
import os
os.path.join('C:\Users\A\Desktop\Repo', filename)
The os module contains many useful methods for directory and path manipulation
Backslash character (\) has to be escaped in string literals.
This is wrong: '\'
This is correct: '\\' - this is a string containing one backslash
Therefore, this is wrong:
'C:\Program Files (x86)\LibreOffice 5\program\soffice.exe'
There is a trick!
String literals prefixed by r are meant for easier writing of regular expressions. One of their features is that backslash characters do not have to be escaped. So, this would be OK:
r'C:\Program Files (x86)\LibreOffice 5\program\soffice.exe'
However, that wont work for a string ending in backslash:
r'\' - this is a syntax error
So, this is also wrong:
r'C:\Users\A\Desktop\Repo\'
So, I would do the following:
import os
import subprocess
soffice = 'C:\\Program Files (x86)\\LibreOffice 5\\program\\soffice.exe'
outdir = 'C:\\Users\\A\\Desktop\\Repo\\'
full_path = os.path.join(outdir, filename)
subprocess.call([soffice,
'--headless',
'--convert-to', 'pdf',
'--outdir', outdir,
full_path])
The problem you have is that your raw string is ending with a single backslash. For reason I don't understand, this is not allowed. You can either double up the slash at the end:
r'C:\Users\A\Desktop\Repo\\'+filename
or use os.path.join(), which is the preferred method:
os.path.join(r'C:\Users\A\Desktop\Repo', filename)
To build on what zanseb said, use the os.path.join, but also \ is an escape character, so your string literal can't end with a \ as it would escape the ending quote.
import os
os.path.join(r'C:\Users\A\Desktop\Repo', filename)
To anyone else stumbling across this question, you can use \ to concatenate a Path object and str.
Use path.Path for paths compatible with both Unix and Windows (you can use it the same way as I've used pathlib.PureWindowsPath).
The only reason I'm using pathlib.PureWindowsPath is that the question asked specifically about Windows paths.
For example:
import pathlib
# PureWindowsPath enforces Windows path style
# for paths that work on both Unix and Windows use path.Path
base_dir = pathlib.PureWindowsPath(r'C:\Program Files (x86)\LibreOffice 5\program')
# elegant path concatenation
myfile = base_dir / "myfile.odt"
print(myfile)
>>> C:\Program Files (x86)\LibreOffice 5\program\myfile.odt
add library to code :
from pathlib import Path
when u want get current path without filename use this method :
print("Directory Path:", Path().absolute())
now you just need to add the file name to it :for example
mylink = str(Path().absolute())+"/"+"filename.etc" #str(Path().absolute())+"/"+"hello.txt"
If normally addes to the first path "r" character
for example: r"c://..."
You do not need to do here
You can also simply add the strings together. Personally I like this more.
filename = r"{}{}{}".format(dir, foldername, filename)
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
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