How to create a file one directory up? - python

How can I create a file in python one directory up, without using the full path?
I would like a way that worked both for windows and linux.
Thanks.

Use os.pardir (which is probably always "..")
import os
fobj = open(os.path.join(os.pardir, "filename"), "w")

People don't seem to realize this, but Python is happy to accept forward slash even on Windows. This works fine on all platforms:
fobj = open("../filename", "w")

Depends whether you are working in a unix or windows environment.
On windows:
..\foo.txt
On unix like OS:
../foo.txt
you need to make sure the os sets the current path correctly when your application launches.
Take the appropriate path and simply create a file there.

Related

How to know where is windows installed with Python?

I am writing a program that needs to know which Drive is Windows drive . because I need to go to "Windows-Drive:\Users\publick\Desktop", I need some code or module that will give me the windows drive.
Thanks for your kindness.
If what you really want is the drive where Windows is installed, use
import os
windows_drive = os.environ['SystemDrive']
But it looks like what you actually need is the public desktop folder. You can get that easier and more reliably like this:
import os
desktop_folder = os.path.join(os.environ['PUBLIC'], 'Desktop')
For the current user's desktop folder instead, you can use this:
import os
desktop_folder = os.path.join(os.environ['USERPROFILE'], 'Desktop')
But I'm not sure that the desktop folder is always called 'Desktop' and that it's always a subdirectory of the profile folder.
There is a more reliable way using the pywin32 package (https://github.com/mhammond/pywin32), but it obviously only works if you install that package:
import win32comext.shell.shell as shell
public_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_PublicDesktop)
user_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_Desktop)
(Unfortunately pywin32 is not exactly well documented. It's mostly a matter of first figuring out how to do things using Microsoft's Win32 API, then figuring out where to find the function within pywin32.)
#!/usr/bin/env python3
# Python program to explain os.system() method
# importing os module
import os
# Command to execute
# Using Windows OS command
cmd = 'echo %WINDIR%'
# Using os.system() method
os.system(cmd) # check if returns the directory [var = os.system(cmd) print(var) ] in Linux it doesnt
# Using os.popen() method
return_value = os.popen(cmd).read()
can you check this approach ? I am not on Win
I found my Answer!
`import os
Windows-Drive=os.path.dirname(os.path.dirname(os.path.join(os.path.join(os.environ['USERPROFILE']))))
This code is answer!

How to use Relative paths in python with, "with open()" and windows cmd or powershell

Here is my code:
from datetime import datetime
now = datetime.now()
date_time = now.strftime("%d-%m-%Y-%H-%M")
with open("Keyboard\Program\log\_temp.txt", "w") as f:
f.write(f"Keyboard\Program\log\log-{date_time}.txt")
im trying to execude this in my windows cmd or ps but all i get is
with open("Keyboard\Program\log_temp.txt", "w") as f:
FileNotFoundError: [Errno 2] No such file or directory:
'Keyboard\Program\log\_temp.txt'
I also tried different solutions from stackoverlow but noething seemed to help for my
If your cwd is: E:\#CodingGameEngine\!Projects\PythonProjects\RandomProjects\Keyboard\Program then you only need to be relative to that:
with open("log\_temp.txt", "w") as f:
Programs, in general, don't know or care where their executable lives. When you run them, you are starting them from some working directory, and all relative pathnames are interpreted from there.
When you start a program from the command line, it's easy to see what your current working directory is (Run pwd in PowerShell or bash, or cd in CMD). When you start a program by double-clicking an icon, however, Windows changes the current working directory to the one containing the program. That's why it's easy to get confused and think relative paths are always relative to the folder containing the program.
If you're writing something to be run from the command-line, you might want to write it to use absolute paths instead of assuming the user will be where you think they are. You can always get the path from an environment variable if you want the user to be able to configure it.

How do I run external programs in Python without using the entire path?

Now, I'm working on a voice controlling assistant application.
When I say "open Google Chrome", it should open Chrome. I do not have any problems with speech recognition but I do have a problem with starting the program.
For example, the following code:
import os
os.system("chrome.exe")
Works fine for the notepad.exe or cmd.exe programs but when I give external programs like chrome, I need to give the entire path.
However, in C# we can only give the direct name like chrome.exe to run the program.
So, my problem is that, is there any ways to start external programs without giving the entire path like in C#?
Giving path to start the program would be a serious problem. Because when we move the program to another computer, we will face many code errors.
Try os.path.abspath
os.path.abspath("chrome.exe")
returns the following:
C:\Users\Yourname\chrome.exe
The PATH system variable governs this inside Python just as outside. If you want to modify it from Python, it's os.environ.
As an aside, a better solution is probably to use subprocess instead, as suggested in the os.system documentation.
The PATH manipulation will be the same regardless.
import os
import subprocess
os.environ['PATH'] = os.environ['PATH'] + r';c:\google\chrome\'
subprocess.run(['chrome.exe'])
... where obviously you need to add the directory which contains chrome.exe to your PATH.
Probably you will want to make sure the PATH is correct even before running Python in your scenario, though.
The first part of this answer is OS specific and doesn't solve it in code or python
Add the path where Chrome exists to your PATH variable (you'll likely need a restart), and then when you execute a command such as chrome.exe it will try to run it from that path location
UPDATE:
If you want to implement a search for the absolute path here are some good resources on path listing How do I list all files of a directory?
But again you'll likely need some educated guesses and will need to do some OS specific things to find it.
The Chrome binary is often installed in the same set of locations
I solved this problem by using C#. Like I already mentioned, we can directly call programs like "chrome.exe" in C#. I created a console application in C# which open Google Chrome via using bellow code. Then I complied that console application as .exe, after that I link that exe file with my python program.
C#
Process ExternalProcess = new Process();
ExternalProcess.StartInfo.FileName = "chrome.exe";
ExternalProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
ExternalProcess.Start();
ExternalProcess.WaitForExit();
Python
import os
os.system('console_application.exe')

Hidden .db files using Python and SQLite3

I am using sqlite3 and python for a new website I am creating. The problem is, the "files_storage.db" file I am trying to create will not appear in any Windows 10 Folder Window, PyCharm's Directory View, nor will it appear via the command line interface.
The catch to this is, if I execute my python script multiple times, I get an error that states the database file already exists... So this file is somewhere, I guess it is a game of cat and mouse to find it.
I have ran into this problem before, but I have ALWAYS been able to find the file via the command line. Usually, I wouldn't both yall with such a question but, this is really irking me and I am going to run into serious issues when it comes time to put this baby on a server. :(
thanks in advance, and here's some screenshots I suppose.
You are using a relative file path.
Relative paths are converted to absolute ones by something like os.path.join(os.getcwd(), <relative path>). So they depend on the current working directory of the process.
Try to open it with an absolute path (starting with drive letter) to avoid any ambiguities.
If you use just a filename without a path, the file will be saved in whatever the current working directory of the Python interpreter is.
To see where the current working directory is, add the following code to the beginning of your program:
import os
print(os.getcwd())
You should then see the working directory in the output.
There is a setting for the current working directory in your IDE somewhere. See e.g. the answers to this question.
You can also do something like:
import os
path = os.path.expanduser("~") + '/Documents'
print(path)
This will allow you to access the directories for the current user. For me, this prints:
'/Users/thomasweeks/Documents'

Find out windows shortcut path

In windows, I can make a number of shortcuts. I want to know whether the program is opened as shortcut, or itself. And finally I hope to know where the shortcuts path location is in my program. Unfortunately, I use python so I hope a solution in python.
__file__ will get you the name of the invoked script. If it is a link, it should change accordingly.
You can check if the file is a link via the following:
import os
islink = os.path.islink(__file__)
islink will contain a boolean value with the answer.
I tested this out on Ubuntu, but this should in theory work on Windows, also, via POSIX.
More info:
https://docs.python.org/2/library/os.path.html#os.path.islink
I'm not quite sure what you mean by this question:
And finally I hope to know where the shortcuts path location is in my
program.

Categories

Resources