I have a wxPython application. I am taking in a directory path from a textbox using GetValue().
I notice that while trying to write this string to a variable:
"C:\Documents and Settings\tchan\Desktop\InputFile.xls",
python sees the string as
'C:\\Documents and Settings\tchan\\Desktop\\InputFile.xls' (missing a slash between "Settings" and "UserName).
More info:
The directory path string is created by the "open file" dialog, which creates a standard 'choose file' dialog you see in any 'open' function in a text processor. The string is written to a textbox and read later when the main thread begins (in case the user wants to change it).
EDIT: I realise that the problem comes from the '\t' being seen as a "tab" instead of normal forward slash. However I don't know how to work past this, since
I suspect there's a different way to get that path from wx that would avoid this issue, since it seems like this would be a fairly common problem. That said, there are a few ways to fix a mangled path like you describe, by converting the string you have to a raw string.
rawpath = "%r" % path
The resulting rawpath will likely be somewhat messy since it will probably add extra escapes to the backslashes and give you something like:
"'C:\\\\Documents and Settings\\tchan\\\\Desktop\\\\InputFile.xls'"
It seems like os.path.normpath will clean that up though.
import os.path
os.path.normpath(rawpath)
not saying this is the correct solution, but you can
x = "C:\tmp".encode('string-escape')
x
'C:\\tmp'
better, if you are using the file dialog
os.path.join(dlg.GetDirectory(),dlg.GetFilename())
where dlg is your dialog
You have to escape the slashes. \\ will store a literal \ in the string:
path = "C:\\Documents and Settings\\tchan\\Desktop\\InputFile.xls"
Related
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')
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/ >>
I have a main file which uses(from the main I do a source) a properties file with variables pointing to paths.
The properties file looks like this:
TMP_PATH=/$COMPANY/someProject/tmp
OUTPUT_PATH=/$COMPANY/someProject/output
SOME_PATH=/$COMPANY/someProject/some path
The problem is SOME_PATH, I must use a path with spaces (I can't change it).
I tried escaping the whitespace, with quotes, but no solution so far.
I edited the paths, the problem with single quotes is I'm using another variable $COMPANY in the path
Use one of these threee variants:
SOME_PATH="/mnt/someProject/some path"
SOME_PATH='/mnt/someProject/some path'
SOME_PATH=/mnt/someProject/some\ path
I see Federico you've found solution by yourself.
The problem was in two places. Assignations need proper quoting, in your case
SOME_PATH="/$COMPANY/someProject/some path"
is one of possible solutions.
But in shell those quotes are not stored in a memory,
so when you want to use this variable, you need to quote it again, for example:
NEW_VAR="$SOME_PATH"
because if not, space will be expanded to command level, like this:
NEW_VAR=/YourCompany/someProject/some path
which is not what you want.
For more info you can check out my article about it http://www.cofoh.com/white-shell
You can escape the "space" char by putting a \ right before it.
SOME_PATH=/mnt/someProject/some\ path
should work
If the file contains only parameter assignments, you can use the following loop in place of sourcing it:
# Instead of source file.txt
while IFS="=" read name value; do
declare "$name=$value"
done < file.txt
This saves you having to quote anything in the file, and is also more secure, as you don't risk executing arbitrary code from file.txt.
If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:
1) Java's build.properties file:
build_path='/home/ec2-user/Name\\ of\\ Directory'
Where ~/ is equal to /home/ec2-user
2) Jenkinsfile:
build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"
I'm new to Python and i'd like to build a script (Python 3) to test electronic modules and save log files.
I'd like to save the logfiles in the following format:
201410log.txt (yearmonthlog.txt)
This is done with the code:
import os
logfile=open(time.strftime('%Y%mlog.txt'), 'a')
logfile.write('This is a test\n\n\n')
This way, every month a new log file is created.
However, i'd like the logfiles to be in in a subdirectory (\logs).
I tried approaches like
logfile=open(time.strftime('\logs\%Y%mlog.txt'), 'a')
and similar things but i couldnt get any of them to work.
I searched trough other questions on stackoverflow (for example: Relative paths in Python ) and elsewhere in the internet, but i couldnt find the right solution.
Could someone point me in the right direction?
(sorry for any mistakes/spelling errors, i'm no native english speaker)
Remove the leading backslash. It makes the path absolute. Beside that, you need to escape a backslash.
logfile = open(time.strftime('logs\\%Y%mlog.txt'), 'a')
or use r'raw string literal':
logfile = open(time.strftime(r'logs\%Y%mlog.txt'), 'a')
For your current path string literal, it does not make problem. But paths like 'a\nb' will not work because \n is interpreted as newline instead of a literal backslash and n.
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))