Change working directory in Python on Windows with backslash - python

I would like to change my working directory in Python. I am on Windows programming in the Sublime IDE. I am using Python 2.7.
The path I would like, harvested directly from my windows explorer, is:
\\CNYC19P20003D\khandler$\Documents\ShortSqueeze
I am aware of the function os.chdir("path").
However, it seems I am having issues with the fact that Python uses '\' as an escape key, and Windows uses '\' to move a folder level down. Here is what I have so far:
import os
if __name__ == '__main__':
path = os.getcwd()
print "Current working directory:"
print path
os.chdir("M:\CNYC19P20003D\khandler$\Documents\ShortSqueeze")
file_object = open("rawData.txt", 'r')
The output of this code is the following:
'\\CNYC19P20003D\khandler$\Documents\ShortSqueeze'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
Current working directory:
C:\Windows
Traceback (most recent call last):
File "\\CNYC19P20003D\khandler$\Documents\ShortSqueeze\practice.py", line 9, in <module>
file_object = open("rawData.txt", 'r')
IOError: [Errno 2] No such file or directory: 'rawData.txt'
Here is what I have tried so far:
os.chdir("M:\\CNYC19P20003D\khandler$\Documents\ShortSqueeze")
os.chdir("\\CNYC19P20003D\khandler$\Documents\ShortSqueeze")
os.chdir("//CNYC19P20003D/khandler$/Documents/ShortSqueeze")
os.chdir("\\CNYC19P20003D\\khandler$\\Documents\\ShortSqueeze")
os.chdir(r"M:\CNYC19P20003D\khandler$\Documents\ShortSqueeze")
Along with many other variations on the same idea.
I spent some time looking at this stackoverflow article: Python os.chdir is modifying the passed directory name. However, it seems his issue was that part of his path had a specific escape code in it, \201. Since I don't have anything like \n or \t, I figured my issue was different.
How can I change my current working directory to my desired path? Is it possible that I have copied my path wrong? Is this an issue with backslashes?

Related

python - error occurs on relative path but not absolute path in macOS

I'm having a strange issue. I'm just trying to do a basic show directory contents for relative path.
Created a test directory on the desktop
test directory contents
test.py
test1 -- folder
sample.txt
contents of test.py
import os
dataDir = "test1"
for file in os.listdir("/Users/username/Desktop/test"):
print(file)
Summary - absolute path
works - in visual studio code
works - macOS terminal python3 /Users/username/Desktop/test/test.py
however when use the variable I get an error:
contents of test.py
import os
dataDir = "test1"
for file in os.listdir(dataDir):
print(file)
Summary - relative path
works - in visual studio code
ERROR - macOS terminal python3 /Users/username/Desktop/test/test.py
Traceback (most recent call last):
File "/Users/username/Desktop/test/test.py", line 4, in
for file in os.listdir(dataDir):
FileNotFoundError: [Errno 2] No such file or directory: 'test1'
I all depends on what folder you are in when you launch the code.
Let's say your .py file is in folder1/folder2/file.py and your test1 folder is folder1/folder2/test1/.... You open a terminal in the folder1 and launch python3 /folder2/file.py. The program is going to check for files in folder1/test1/.
Try navigating to the actual file folder, that should work. If you want to use it wherever you launch the code you will have to do some checks on the current directory and manually point the code to the wanted path.
The following solution is inspired by that answer
A simple way to solve your problem is to create the absolute path. (I recommend using that always when you're working with different directories and files)
First of all, you need to care about your actual working directory. While using VS Code your working directory is in your desired directory (/Users/username/Desktop/test/).
But if you use the command line your actual working directory may change, depending where you're calling the script from.
To get the path where script is actually located, you can use the python variable __file__. __file__ is the full path to the directory where your script is located.
To use your script correctly and being able to call it using both ways, the following implementation can help you:
import os
dataDir = "test1"
# absolute path to the directory where your script is in
scriptDir = os.path.dirname(__file__)
# combining the path of your script and the 'searching' directory
absolutePath = os.path.join(scriptDir, dataDir)
for file in os.listdir(absolutePath):
print(file)

python code can't find file while its in folder marked as resource root in PyCharm

In PyCharm, I created folder named test, created txt file named test inside and marked folder as content root. When I added python file outside the test folder and tried to access test.txt file with open it suggested me file name. But when I tried running the code it couldn't find the file.
Traceback (most recent call last):
File "/home/elmo/PycharmProjects/TBC_PAY_API_TESTING/testing.py", line 32, in <module>
print(open("test.txt").read())
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
This is how the code and folders look like ( ingore the trash folder)
How can I fix it? The main reason I am doing this is to avoid writing full path's for accessing file.
You are talking about two totally different things in your question. If you mark a folder as Sources root that means the Python interpreter will be able to find the modules in that folder.
For example:
When you write an own module and you want to use it in another file the Python won't find it automatically. The PYTHONPATH should contain the path of the folder which contains your module. And actually the Sources root option does this!
The other thing what you have mentioned in your question is that you don't provided a correct path in your code. It is a real error. In your code, you have to provide the correct path for open. The Pycharm is an IDE but your (or other's) Python interpreter will use your code.
You can solve your problem in many ways.
For example:
You can hard-code the path of your txt (It is totally not recommended):
print(open("/home/elmo/PycharmProjects/TBC_PAY_API_TESTING/test/text.txt").read())
You can use relative path:
print(open("test/text.txt").read())
You can use full path based on your Python file (I recommend this solution):
import os
dir = os.path.realpath(os.path.dirname(__file__)) # Directory of your Python file
file_path = os.path.join(dir, "test", "test.txt") # Create the path of the file
print(open(file_path).read())

how do i get current working directory in atom

In atom, os.getcwd() always returns D:\WorkSpace\Test. So if I do things like open("01.txt"), it cannot find the file.
Also, this happens when using the "script" package to execute in Atom, But when executing the actual python file, it works.
I have found several other asking the same question, like this, but there is still no resolution.
Thanks to everyone who tried to help!
Added my directory:
D:\WorkSpace\Test
D:\WorkSpace\Test\01\01.py
D:\WorkSpace\Test\01\01.txt
or
D:\WorkSpace\Test
└─01
└─ 01.py
└─ 01.txt
Added my source:
01.py
import os
print os.getcwd()
f = open("01.txt")
print f.read()
01.txt
atom editor 01.txt
Added results(in atom):
D:\WorkSpace\Test
Traceback (most recent call last):
File "D:\WorkSpace\Test\01\01.py", line 5, in <module>
f = open("01.txt")
IOError: [Errno 2] No such file or directory: '01.txt'
Added results(in windows cmd):
D:\WorkSpace\Test\01>01.py
D:\WorkSpace\Test\01
atom editor 01.txt
In Mac, I solved this kind of issue by opening ATOM from a shell window, under target directory. Seems ATOM will use the directory it inherited from shell process as its working directory. You might try with a windows cmd window, see if it works.
Windows - go to Packages -> Settings View -> Manage Packages. Then go to System Settings on the left hand side menu and tick 'Show in file context menus'.
You can now go to your chosen directory and open any file (.js, .py etc.) with Atom and the current working directory will change to the one you chose instead of the default .atom.

Full File Path vs. Short OSX

I'm running OSX Mavericks but this problem has been going on since I had Snow Leopard.
When writing a script in any language, eg: Python. When I try to open a file the short
form doesn't work.
file = open('donkey.jpg')
And I get this error:
IOError: [Errno 2] No such file or directory: 'donkey.jpg'
Instead, I always have to specify the full path.
file = open('/Users/myName/Desktop/donkey.jpg')
Any ideas on why this could be happening and how to correct it?
If you specify donkey.png, it means donkey.jpg file in the current working directory. (relative path)
Make sure you're running the script in the same directory where donkey.jpg exists.
If you want specify the image file path relative to the script file instead of current working directory use following:
import os
filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'donkey.jpg')
NOTE You can use __file__ only in script file. (not in interactive mode)
Your open call does not have a mode parameter. In which case, it defaults to opening the file in read mode.
Unless the file you are opening (to read) resides in the current working directory, it is completely expected that the python script throws a IOError.

Error getting abspath for Windows 7 with Python

I keep getting a 'cannot find file' error when trying to run this. Why is it not finding and assigning the absolute path? Here is my code:
file = "/" + arr[2] + ".exe"
print(file)
path = os.path.abspath(file)
print(path)
subprocess.Popen(path)
localtime = time.asctime(time.localtime(time.time()))
print(arr[2] + " opened at " + localtime + "\n")
Here is what is outputted:
/firefox.exe
C:\firefox.exe
Traceback (most recent call last):
File "C:\Python33\lib\subprocess.py", line 1090, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I am trying to programmatically find open a program based on user input... Maybe I am going about that the wrong way, but this is how somebody suggested doing it. Firefox.exe should be located at C:/Program Files/Firefox/firefox.exe
Any help would be great! Thanks!
One solution for attempting to open a program on Windows is to just search all folders, starting from the base directories of C:/Program files/ and C:/Program Files (x86). A simple solution to this might be something like the following:
for program_files in (os.path.join("C:", "Program\ Files"), os.path.join("C:", "Program\ Files\ (x86)"):
for dir in os.listdir(program_files):
if os.path.exists(os.path.join(program_files, dir, arr[2]) + ".exe"):
subprocess.Popen(os.path.join(program_files, dir, arr[2]) + ".exe")
This only walks one directory down into the Program Files directories, but it should at least give a gist of what needs to be done, as well as provide a simple solution for most cases. I would assume that most programs tend to keep their executable under the first directory.
As a quick side note: if you are creating an application that can be run on both 32bit and 64bit versions of Windows, you will want some kind of check for the existence of the Program Files (x86) directory, or some kind of check for 32 vs 64 bit Windows. That folder only exists on 64 bit versions of Windows.
Also: the reason your method didn't work is because you were getting the abspath of /firefox.exe, which on a Unix system signifies the lowest-level directory on the computer. On Windows, that would be C:/. Python generally works in a very Unix-ey way, so it assumes you wanted the root directory of your system.
Once I had attianed the paths this is how I would launch the programs, however file walking/search algorithms is beyond the scope of this question.
#load this from a setting file later
programDict = {'firefox': r"C:/Program Files/Firefox/firefox.exe"}
if sys.argv[2] in programDict:
subprocess.Popen(path)

Categories