Python, make filename based on path and replace backslash - python

I'm using Linux and in Python, I want to create a file name based on a path. Imagine I have the path:
'/a/b/c'
I want to create a string from this where the slashes are replaced with an underscore character:
'a_b_c'
This is easy enough with replace:
'a/b/c/.replace('/', '_')
But I worry that this would not work on windows. I don't know much about windows paths. Is there a straightforward way to make this operation windows-compatible? Either through os.path functions, or through another replace call?
Thanks

Try using
import os
out='a/b/c/'.replace(os.path.sep, '_')
print out

Related

Can't replace character "\"

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/ >>

Jupyter note book path not found

I have tried to locate the file. used both forward and backwards also I have used 1 and 2 apostrophes - nothing has changed
This is the error I am getting
Windows is a bit trickier. This is jut a hunch but maybe try:
path = "C:\\Users\\BarbieA\\.... "
Windows paths are separated by \ but since that is used to escape special characters, you would need to escape it as well, so it becomes \\
Yeah. I recommend using pathlib to make your life easier, as sometimes, the spaces and the special symbols can be confusing when writing by hand.
from pathlib import PureWindowsPath
file = PureWindowsPath(r"C:\Users\Barbie..")
open(file)

How to correctly decode window path in python

I have a question on correctly decode a window path in python. I tried several method online but didn't find a solution. I assigned the path (folder directory) to a variable and would like to read it as raw. However, there is '\' combined with number and python can't read correctly, any suggestion? Thanks
fld_dic = 'D:TestData\20190917_DT19_HigherFlowRate_StdCooler\DM19_Data'
I would like to have:
r'D:TestData\20190917_DT19_HigherFlowRate_StdCooler\DM19_Data'
And I tried:
fr'{fld_dic}' it gives me answer as: 'D:TestData\x8190917_DT19_HigherFlowRate_StdCooler\\DM19_Data'
which is not what I want. Any idea how to change to raw string from an assigned variable with '\' and number combined?
Thanks
The problem's root caused is string assigning. When you assigning like that path='c:\202\data' python encode this string according to default UNICODE. You need to change your assigning. You have to assige as raw string. Also like this path usage is not best practice. It will occure proble continuesly. It is not meet with PEP8
You should not be used path variable as string. It will destroy python cross platform advantage.
You should use pathlib or os.path. I recommend pathlib. It have pure windows and linux path. Also while getting path use this path. If You get path from and input you can read it as raw text and convert to pathlib instance.
Check this link:
https://docs.python.org/3/library/pathlib.html
It works but not best practice. Just replace path assigning as raw string/
import os
def fcn(path=r'C:\202\data'):
print(path)
os.chdir(path)
fcn()

Why "os.path.join" and "os.path.dirname(__file__)" return different separator?

I'm a beginner.
My system is win10 Pro,and I use python3.X.
I use this code to test function "os.path.join()" and "os.path.dirname()".
import os
print(os.path.join(os.path.dirname(__file__), "dateConfig.ini"))
The output is:
E:/test_opencv\dateConfig.ini
I found os.path.join() use "/",but os.path.dirname() use "\",why?
If I want to use the same separator,all is '/' or '\',what should I do?
that's because __file__ contains the script name as passed in argument.
If you run
python E:/test_opencv/myscript.py
then __file__ contains exactly the argument passed to python. (Windows has os.altsep as /, because it can use this alternate separator)
A good way of fixing that is to use os.path.normpath to replace the alternate separator by the official separator, remove double separators, ...
print(os.path.join(os.path.normpath(os.path.dirname(__file__)),"dateConfig.ini"))
Normalizing the path can be useful when running legacy Windows commands that don't support slashes/consider them as option switches. If you just use the path to pass to open, you don't need that.

File path with double slashes python

I want to be able to get the file path of a python executable:
import os,sys
path=os.getcwd()+'\\'+sys.argv[0]
I want to check if path is a valid path with os.path.isfile().However this doesnt work as the path variable returned has single slashes. Python for some reason cant detect paths with single slashes. How can I make all the single slashes() double slashes(\).I want to make C:\path\to\file to C:\\path\\to\\file. python can't use the .replace() for single quotes so what other way can I get a path with double slashes
With no other caveats, those slashes are read as escape characters. You can, for example, use the raw prefix (i.e. r'\' instead of '\') for replace as a fix.
That's still being inefficient though - your code will break on different OSes this way - you should use os.path module's path operations instead.

Categories

Resources