To move some files i am using this code:
import glob
import os
import shutil
list_of_files = glob.glob('C:/Users/user/staff/*')
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
filename= os.path.basename(latest_file)
shutil.move(latest_file, f"C:\\Users\\user\\test folder\\{filename}"
The code works and the file has moved but i would like to know if this actually matters:
The file which was moved is this:
C:/Users/user/staff\Aug-2021.csv
Notice the slash is now backward instead of forward. Does the orientation of slash matter or would matter in future when my code becomes more complicated(for best practices) or is this how it is suppose to work?
Both will work, but mixing slash and backslash is at least ugly. If you want to do something os independent, you can use os.sep to get the seperation character of your os.
>>> import os
>>> os.sep
'\\'
With this you could do something like
>>> os.sep.join(['foo','bar'])
'foo\\bar'
But you can also use os.path.join to build the path and let python handle that problem for you.
>>> import os
>>> os.path.join(os.getcwd(),'foo.bar')
'C:\\Users\\Me\\foo.bar'
Both foward or backslash are perfectly valid path separators. Also, it is a good practice to include 'r' before a path string:
r'C:\Users\user\staff\Aug-2021.csv'
The means your string will be treated as a raw string. You can see string literals reference here
Both works same but try to use \ slash to avoid 0.1 chance of error.
And I also get error of encoding so add r before the path eg : r"C:\\Users\\user\\test folder\\{filename}" .
Hope that answers the question.
Related
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
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/ >>
There has been multiple discussions about the issue when dealing with trailing slashes in pathlib.Path, on Unix systems in particular such as https://bugs.python.org/issue21039 and https://bugs.python.org/issue39140.
Given the pathlib.Path constructed from a string, I wonder what would be the best way to make sure a trailing slash is preserved in the Path object the same way the os module does it?
>>> os.path.dirname("/a/b/")
'/a/b'
>>> os.path.dirname("/a/b")
'/a'
os module understands the difference between "/a/b/" and "/a/b", but pathlib doesn't:
>>> Path("/a/b/").parent
PosixPath('/a')
Is there any way to be able to differentiate between paths that are pointing to a file (without a trailing slash) and to a directory (that has a trailing slash)? Or I'd have to switch to using os module in this particular case?
If it's not possible, what would be a reasonable workaround to take advantage of pathlib and deal with the trailing slash issue?
This looks like a low-level path manipulation, I would go with the os module (as suggested by the pathlib documentation)
This would add the trailing slash, OS independently:
os.path.join(os.path.abspath("/a/b/"), "")
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)
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