File path with double slashes python - 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.

Related

Opening files in python3 for windows10

Hi I cannot open files in python 3 actually I have a problem with the path. I don't know how to write the path for it.:/ For example I have a file(bazi.py) in folder(w8) in driver(F). How should i write it's path. Please help me im an amateur:/
In Windows, there are a couple additional ways of referencing a file. That is because natively, Windows file path employs the backslash "" instead of the slash. Python allows using both in a Windows system, but there are a couple of pitfalls to watch out for. To sum them up:
Python lets you use OS-X/Linux style slashes "/" even in Windows. Therefore, you can refer to the file as 'C:/Users/narae/Desktop/alice.txt'. RECOMMENDED.
If using backslash, because it is a special character in Python, you must remember to escape every instance: 'C:\Users\narae\Desktop\alice.txt'
Alternatively, you can prefix the entire file name string with the rawstring marker "r": r'C:\Users\narae\Desktop\alice.txt'. That way, everything in the string is interpreted as a literal character, and you don't have to escape every backslash.
File Name Shortcuts and CWD (Current Working Directory)
So, using the full directory path and file name always works; you should be using this method. However, you might have seen files called by their name only, e.g., 'alice.txt' in Python. How is it done?
The concept of Current Working Directory (CWD) is crucial here. You can think of it as the folder your Python is operating inside at the moment. So far we have been using the absolute path, which begins from the topmost directory. But if your file reference does not start from the top (e.g., 'alice.txt', 'ling1330/alice.txt'), Python assumes that it starts in the CWD (a "relative path").
using the os.path.abspath function will translate the path to a version appropriate for the operating system.
os.path.abspath(r'F:\w8\bazi.py')

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

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.

Why is glob ignoring some directories?

I'm trying to find all *.txt files in a directory with glob(). In some cases, glob.glob('some\path\*.txt') gives an empty string, despite existing files in the given directories. This is especially true, if path is all lower-case or numeric.
As a minimal example I have two folders a and A on my C: drive both holding one Test.txt file.
import glob
files1 = glob.glob('C:\a\*.txt')
files2 = glob.glob('C:\A\*.txt')
yields
files1 = []
files2 = ['C:\\A\\Test.txt']
If this is by design, is there any other directory name, that leads to such unexpected behaviour?
(I'm working on win 7, with Python 2.7.10 (32bit))
EDIT: (2019) Added an answer for Python 3 using pathlib.
The problem is that \a has a special meaning in string literals (bell char).
Just double backslashes when inserting paths in string literals (i.e. use "C:\\a\\*.txt").
Python is different from C because when you use backslash with a character that doesn't have a special meaning (e.g. "\s") Python keeps both the backslash and the letter (in C instead you would get just the "s").
This sometimes hides the issue because things just work anyway even with a single backslash (depending on what is the first letter of the directory name) ...
I personally avoid using double-backslashes in Windows and just use Python's handy raw-string format. Just change your code to the following and you won't have to escape the backslashes:
import glob
files1 = glob.glob(r'C:\a\*.txt')
files2 = glob.glob(r'C:\A\*.txt')
Notice the r at the beginning of the string.
As already mentioned, the \a is a special character in Python. Here's a link to a list of Python's string literals:
https://docs.python.org/2/reference/lexical_analysis.html#string-literals
As my original answer attracted more views than expected and some time has passed. I wanted to add an answer that reliably solves this kind of problems and is also cross-plattform compatible. It's in python 3 on Windows 10, but should also work on *nix systems.
from pathlib import Path
filepath = Path(r'C:\a')
filelist = list(filepath.glob('*.txt'))
--> [WindowsPath('C:/a/Test.txt')]
I like this solution better, as I can copy and paste paths directly from windows explorer, without the need to add or double backslashes etc.

Python, make filename based on path and replace backslash

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

Categories

Resources