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.
Related
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.
I have the following code:
import datetime as date
import os
import pdfkit
import getpass #Gets me current username
username = getpass.getuser()
path = f"/home/{username}/Data"
relative_path = os.path.relpath(path, os.getcwd())
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{destination}/data.pdf')
I want the pdf to be saved in windows equivalent of /home/[username]/datafolder. I don't really need to use use linux or mac but for academic reasons i have decided to use the relative path method.
This code makes sense to me but for some reason it is not the directory i want it to be because when i specify the path this way the pdf generator, generates an error.
Error: Unable to write to destination
Exit with code 1, due to unknown error.
I know the error is in the last line of code where i have specified '/relative_path/data.pdf'. Could you please advise how i can resolve this issue?
Update 1:
As suggested by #Matthias I have updated the code but I am still getting the same error
Update 2:
I tried:
from pathlib import Path
destination = Path.home()
try:
os.mkdir(destination\Data)
except OSError as error:
print(error)
But it is still not pointing to the directory Data
Update 3
I know i am getting closer:
import pdfkit
import datetime as date
import calendar
import os.path
import getpass
username = getpass.getuser()
path = f"/home/{username}/Data"
os.makedirs(relative_path, exist_ok=True)
#start = os.getcwd()
relative_path = os.path.relpath(path, os.getcwd())
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
At this point the code is executes but the folder Data was not created not am i able to locate data.pdf. I did get sucessful run though:
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
Any ideas on how i can get this working correctly? The code does not produce the folder or the file?
Just check by putting
relative_path line before os.makedirs
As below
import pdfkit
import datetime as date
import calendar
import os.path
import getpass
username = getpass.getuser()
#path = os.path.join("home","{username}","Data")
# in case of window you will need to add drive "c:" or "d:" before os.path.sep
path = os.path.join(,"home",username,"Data")
relative_path = os.path.relpath(path, os.getcwd())
os.makedirs(relative_path, exist_ok=True)
#start = os.getcwd()
destination = os.path.join(relative_path, 'data.pdf')
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
Maybe you could change your last line to:
pdfkit.from_url('www.google.com', f'{relative_path}/data.pdf')
in order to get it to save to the home directory.
Perhaps the issue is that the directory doesn't exist. You could use os.makedirs to create the directory, using the exist_ok=True flag in case the directory already exists. Like so:
import datetime as date
import os
import pdfkit
import getpass #Gets me current username
username = getpass.getuser()
path = f"/home/{username}/Data"
os.makedirs(path, exist_ok=True)
pdfkit.from_url('www.google.com', f'{path}/data.pdf')
You can use os.environ. Run this little script on your machine:
import os
for key, value in os.environ.items():
print(key, '-->', value)
and see for yourself what you need exactly. It's portable as well.
Let's say you want to get the path of the user's home directory. You could get it from os.environ['HOME'] and then create the path to the target directory using os.path.join(os.environ['HOME'], 'target_directory_name').
You won't be able to create files in a directory if you don't have the required permissions, though.
User folders in windows are stored in "/Users/{username}/*". I don't know if you are trying to make this compatible for multiple OSs but if you just want to make this run on windows try:
path = f"/Users/{username}/Data"
start = f"/Users/{username}"
Hope it works.:)
Edit:
To get the home directory of a user regardless of OS you could use
from pathlib import Path
home = str(Path.home())
sorry for the late edit.
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 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)
I use the below python script to check if a file exist on the root of my ftp server.
from ftplib import FTP
ftp = FTP('ftp.hostname.com')
ftp.login('login', 'password')
folderName = 'foldername'
if folderName in ftp.nlst() :
print 'YES'
else : print 'NO'
How can I modify the above script to look inside a specific folder instead of the root directory?
For example, I want to see if a folder name called foo exists inside the www directory.
The goal of my question, is to see if the folder foo exists inside the www directory, if so print cool! if not create a folder called foo inside www.
from ftplib import FTP
ftp = FTP('ftp.hostname.com')
ftp.login('login', 'password')
where = 'www'
folderName = 'foldername'
if folderName in ftp.nlst(where) :
print 'YES'
else :
print 'NO'
Just send the directory you want to see in as first argument of ftp.nlst()
After the hint from Hans! I searched on google for those commandes and I found this link : http://docs.python.org/2/library/ftplib.html
from ftplib import FTP
ftp = FTP('ftp.hostname.com')
ftp.login('login', 'passwrd')
ftp.cwd('www') # change into 'www' directory
if 'foo' in ftp.nlst() : #check if 'foo' exist inside 'www'
print 'YES'
ftp.cwd('foo') # change into "foo" directory
ftp.retrlines('LIST') #list directory contents
else :
print 'NO'
ftp.mkd('foo') #Create a new directory called foo on the server.
ftp.cwd('foo') # change into 'foo' directory
ftp.retrlines('LIST') #list subdirectory contents
ftp.close() #close connection
ftplib is a rather thin wrapper around the FTP protocol. You can look at http://en.wikipedia.org/wiki/List_of_FTP_commands to see what the FTP commands do.
Hint: look at CWD, LIST, MKD.
For LIST you will need ftp.retrlines and parse it to see if it is a directory.