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/ >>
Related
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)
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.
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.
I have tried so many variants of a theme to get this explorer window open at the P:\ drive, from what my little knowledge tells me, the fact the path to the folder is anywhere but the C:\ drive means it fails (it works with C:) so perhaps the path is wrong? the code below shows some of the tries i have made but still no luck, "P:" is mapped the same on all machines.
def Open_Win_Explorer_and_Select_Dir():
import subprocess
fldrname = os.path.basename(currentproject.get())
print(fldrname)
#subprocess.Popen('c:\windows\EXPLORER.EXE', cwd=(P:/Projects 2013/)
#subbprocess.Popen('c:\\windows\\EXPLORER.EXE' cwd=('P:\\Projects_2013\\')fldrname)
#subprocess.Popen(r'C:/Windows/explorer.exe', cwd=r'//WRDBSVR/Project_Data/Projects_2013/'+fldrname)
subprocess.Popen('explorer /n, /select r"\\192.168.0.27\\Project_Data\\Projects_2013\\"'+fldrname)
#subprocess.Popen('explorer /n, /select r"P:\\Project_Data\\Projects_2013\\"'+fldrname)
well to open My pc (for windows) try:
import subprocess
subprocess.Popen('explorer ""')
"#if subprocess.Popen('explorer "{0}".format(full_path)') is struck at pc\my documents.
where full_path=os.path.join("your/path")"
Appart from the fact that Ashish Nitin Patil's answer is definitly better, as using a variable for paths is always a good idea, you have a problem with your quotes:
# This line is not correct
'explorer /n, /select r"\\192.168.0.27\\Project_Data\\Projects_2013\\"'+fldrname
# ^you start a new string without ending previous one
# this one is correct
'explorer /n, /select ' + r'\192.168.0.27\Project_Data\Projects_2013\' + fldrname
# ^first ending string start
Besides, using raw strings (r"xxx") means that \ will not escape characters, so you shall not double them. If you want to double them, you do not need prepend r.
Last remark: take care to avoid string concatenation (+) when working with paths; you should use os.path.join() instead.
Following should do the job.
import subprocess
subprocess.Popen('explorer "{0}"'.format(full_folder_path))
Update -
Tested on my system -
full_path = os.path.join("P:/Project_Data/Projects_2013/",fldrname)
print full_path # Verify that it is correct
subprocess.Popen('explorer "{0}"'.format(full_path))
I am complete newbie in Python and have to modify existing Python script. The script copies file to other path like following:
err=shutil.copyfile(src, dst)
This works unless dst contains character like &:
dst = "Y:\R&D\myfile.txt"
In this case I get windows error popup that says
Open file or Read file error
Y:\R
I tried to escape & using back slash, double back slash and wrapping the string with additional quotes: dst = "\"Y:\R&D\myfile.txt\"".
Nothing works in last case I get "invalid path" error message from shutil.
How can I solve this problem?
I doubt that ampersand is supported on most platforms. You will likely have to make a call to a windows specific program. I suggest robocopy since its really good at copying files. If it's not included in your version of windows, you can find it in the windows server administrator toolkit for 2003.
It works for me if I change all the \ in the filepaths to / (in both src and dst strings). Yes, I know you're using Windows, but filepaths always seem to be less fussy in Python if you use /, even in Windows.
Also, it looks like you're copying to a network drive. Do you get the same problem copying to c:\R&D\?
What flavor of Windows are you using? shutil.copyfile() works fine for me with & in directory names, in both src and dst paths, in both local and network drives on XP -- as long as I use / in place of \.
Easiest solution, signify to python that the string is raw and not to escape it or modify it in any way:
import shutil
src = r"c:\r&d\file.txt"
dst = r"c:\r&d\file2.txt"
err=shutil.copyfile(src, dst)
Try to escape the "\" with "\ \", this command must work (for example):
shutil.copyfile("Y:\\R&D\\myfile.txt", "C:\\TMP")
Here are few ways to make it work on windows:
Approach 1: (already explained)
import shutil; shutil.copy(src,dest)
as long as src/dest are using r'c:\r&d\file' string format. It also works with forward "/" slashes as well.
Approach 2: Notice use of double quotes instead of single quotes on windows.
src = r'c:\r & d\src_file'
os.system('copy "{}" "{}"'.format(src,dest))
1 file(s) copied
Last resort:
with open(dest, 'wb') as f:
f.write(open(src,'rb').read())
Unlike os.system, this preferred implementation subprocess.call could not work with any quoting approach on windows. I always get The specified path is invalid. Did not try on unix.