I want to Open a file located inside a folder, that is in the same directory as the python script.
For example:
main.py
image_folder
image_1
image_2
image_3
Right now i would type open(image_1.png), or I would type open(C:\Users\user_name\Desktop\main_folder\image_folder\image_1).
But i would wish to make it so that the user name doesn't need to be filled out for a different user.
Is there a simple way to open a file inside a folder in the same directory as the script file?
You could do the following:
import os
username = os.getlogin()
So that the username your signed in to comes up.
Then you could replace user_name with the username variable.
Related
Suppose, if I wanted to open chrome using python. I would require the path of "chrome.exe". My python program does this by searching through the chrome directory in program files.
If I don't want to search through the directory, every single time I run the program. I assume that I must save the path of "chrome.exe" somewhere.
Where should I do so? Should I just store it in a .txt file in the same folder as my program, or do I store it somewhere else? I don't want anyone to alter the path, as such it causes an error in my program. How do I store it somewhere permanent, that no one can edit it except my program?
Why not save the path in this python program then you can call get() with the path to Chrome.
Replace chrome_path with the correct path for your platform.
import webbrowser
url = 'http://docs.python.org/'
# Windows
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
# MacOS
#chrome_path = 'open -a /Applications/Google\ Chrome.app %s'
# Linux
# chrome_path = '/usr/bin/google-chrome %s'
webbrowser.get(chrome_path).open(url)
Hey and thanks for all of your answers. I try to write a piece of python code that only executes once, (first time the program is installed) and copies the program into the windows startup folders.
(C:\Users\ USER \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup)
That's the code i wrote for this. (Please don't judge me. I know it's
very shitty code. But I'm very new to coding. (this is the second
little program i try to write)
import os
import shutil
#get username
user = str(os.getlogin())
user.strip()
file_in = ('C:/Users/')
file_in_2 = ('/Desktop/Py Sandbox/test/program.py')
file_in_com = (file_in + user + file_in_2)
folder_seg_1 = ('C:/Users/')
folder_seg_2 = ('/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup')
#create FolderPath
folder_com = (folder_seg_1 + user + folder_seg_2)
shutil.copy2(file_in_com, folder_com)
Because i got an error, that there is no such internal, external,
command, program or batch file named Installer. I tried to generate a batch file with
nothing in it that executes when the installation process is finished.(But the error is still there.)
save_path = 'C:/Windows/assembly/temp'
name_of_file = str("Installer")
completeName = os.path.join(save_path, name_of_file+".bat")
file1 = open(completeName, "w")
file1.close()
The main idea behind this that there is my main Program, you execute
it it runs the code above and copies itself to the startup folder.
Then the code the whole installer file gets deleted form my main
program.
import Installer
#run Installer File
os.system('Installer')
os.remove('Installer.py')
But maybe there's someone out there who knows the answer to this problem.
And as I said earlier, thanks for all of your answers <3.
BTW I'm currently using Python 3.5.
Okay guys now I finally managed to solve this problem. It's actually not that hard but you need to think from another perspective.
This is now the code i came up with.
import os
import sys
import shutil
# get system boot drive
boot_drive = (os.getenv("SystemDrive"))
# get current Username
user = str(os.getlogin())
user.strip()
# get script path
script_path = (sys.argv[0])
# create FolderPath (Startup Folder)
folder_seg_1 = (boot_drive + '/Users/')
folder_seg_2 = ('/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup')
folder_startup = (folder_seg_1 + user + folder_seg_2)
#check if file exits, if yes copy to Startup Folder
file_name = (ntpath.basename(script_path))
startup_file = (folder_startup + ("/") + file_name)
renamed_file = (folder_startup + ("/") + ("SAMPLE.py"))
# checkfile in Startup Folder
check_path = (os.path.isfile(renamed_file))
if check_path == True:
pass
else:
shutil.copy2(script_path, folder_startup)
os.rename(startup_file, renamed_file)
This script gets your username, your boot drive, the file location of
your file than creates all the paths needed. Like your personal
startup folder. It than checks if there is already a file in the
startup folder if yes it just does nothing and goes on, if not it
copies the file to the startup folder an than renames it (you can use that if you want but you don't need to).
It is not necessary to do an os.getenv("SystemDrive") or os.getlogin(), because os.getenv("AppData") already gets both. So the most direct way of doing it that I know of is this:
path = os.path.join(os.getenv("appdata"),"Microsoft","Windows","Start Menu","Programs","Startup")
I am working on a script to get information from the Skype database.
I got the following code:
con = sqlite3.connect('C:\\Users\\joey\\AppData\\Roaming\\Skype\\jre93\\main.db')
But the skype ID (jre93) and the USER (joey) of the computer are always different. Is there a way python can recognize those path automatic with out user input?
Usually the folder with name of skype ID contains the main.db file!
So we can use this fact to get the skype ID.
One method to do so is to first check if there is any skype folder at that particular path. Then find the folder in the skype folder, that contains the main.db file. If a folder is found then the name of this folder is the skype ID.
I have created a small quick and dirty script for this work. (It can be further improved)
Code:
import getpass
import os
import sys
userName = getpass.getuser() #Get the username
path = "C:\\Users\\"+userName+"\\AppData\\Roaming\\Skype\\"
if (os.path.isdir(path)) == True: #Check if Skype folder exists
subdirectories = os.listdir(path)
for i in subdirectories:
if os.path.isdir(path+i) == True:
if os.path.exists(path+i+"\\main.db"):
print ("Skype Id is %s") %i
else:
print 'Skype folder does not exists'
I hope it was helpful.
I'm working on a program to open a folder full of images, copy the images, and then save the copies of the images in a different directory.
I am using Python 2.4.4, but I am open to upgrading the program to a newer version if that allows me to import PIL or Image because I cannot do that with my version.
As of now, I have:
import Image
import os
def attempt():
path1 = "5-1-15 upload"
path2 = "test"
listing = os.listdir(path1)
for image in listing:
im = Image.open(path1)
im.save(os.path.join(path2))
I am new to Python, so this is probably obviously wrong for numerous reasons.
I mostly need help with opening a folder of images and iterating through the pictures in order to save them somewhere else.
Thanks!
Edit- I've tried this now:
import shutil
def change():
shutil.copy2("5-1-15 upload", "test")
And I am receiving an IOError now: IOError: System.IO.IOException: Access to the path '5-1-15 upload' is denied. ---> System.UnauthorizedAccessException: Access to the path '5-1-15 upload' is denied.
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in :0
Am I entering the folders wrong? How should I do this if it an a folder within a specific computer network.
Basically there is a folder called images with multiple subfolders within it which I am trying to extract the images from.
Based on this answer, copyfile will do the trick, as you are just copying images from one side to another, as if it was another type of file.
import shutil
import os
def attempt():
path1 = "5-1-15 upload"
path2 = "test"
listing = os.listdir(path1)
for image in listing:
copyfile(image, path2)
i work on python. I have written some codes that i could run via dropbox on different computers( having their various usernames). like this
computer 1:
file=open("/User/james/Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
computer 2:
file = open("/User/oyebodmas/Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
each time i have to switch between computers. i always have to change the usename from james to oyebodmas and vice versa. how could i program the computer to ignore the username and read the file. i have tried
file = open("~/Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
but it does not work. thank you.
For a multiplatform solution, you can do this, assuming the folders you want to access are user's home folders:
import os
home = os.path.expanduser("~")
file_location = os.path.join(home, "Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
myfile = open(file_location)
In the case they are not, and the path is always the same and differs only in the username, you can build the path as shown in TimPietzcker's answer.
I'm not on a *NIX system, so I can't test this, but could you try
import os
currentuser = os.getusername()
file_location = os.path.join("/User", currentuser)
file_location = os.path.join(file_location, "Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
myfile = open(file_location)