WinError 5 access is denied - renaming files - Python - python

I have been trying to create an executable for a simple file name converter.
the goal is to rename all files from a certain directory to their creation date (for images).
import datetime
import os
from tkinter.filedialog import askdirectory
path = askdirectory(title='Select Folder') # shows dialog box and return the path
os.chdir(path)
files = os.listdir(path)
for filename in files:
time_stamp = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
os.rename(filename, time_stamp.strftime('%d-%m-%Y %H-%M-%S') + ".jpg")
It works perfectly where I run it through PyCharm, but when I run it through the executable that I created using pyInstaller, I get "[WinError 5] access is denied". The premission error occures because of the os.rename() function.
I tried to run it as an administrator but I got the same result.
I also updated my python, pycharm and pip but that had no effect.
Is there a way to make this script an executable?
thank you all

Related

opening a .txt file

first, i'd like to mention that im using python via visual studio. not sure if this information will
be relevant but this is my first time using file input so i'm not sure
basically, i have a .txt file located in the same location as my .py file. however, when i go to access it, i get an error 'FileNotFoundError: [Errno 2] No such file or directory'
is there a way to make it work or a different IDE i should use?
I tried reading a .txt file from the same location as my .py file. however, i keep getting the error 'FileNotFoundError: [Errno 2] No such file or directory'
Take into account that the script might not be running from the same path where your python script is and most probably your are not specifying the exact path of the file.
If your file is located in the same directory where your python sript is you can use the pathlib library this way to get your script to work:
import pathlib
# Some custom code
# find your current script path
current_script_path = pathlib.Path(__file__).parent
my_file_name = "my_file_name.txt"
# Specify the file path relative to your script's path
my_file_path = current_script_path / my_file_name
with open(my_file_path, "r+") as f:
print(f.read())

python - error occurs on relative path but not absolute path in macOS

I'm having a strange issue. I'm just trying to do a basic show directory contents for relative path.
Created a test directory on the desktop
test directory contents
test.py
test1 -- folder
sample.txt
contents of test.py
import os
dataDir = "test1"
for file in os.listdir("/Users/username/Desktop/test"):
print(file)
Summary - absolute path
works - in visual studio code
works - macOS terminal python3 /Users/username/Desktop/test/test.py
however when use the variable I get an error:
contents of test.py
import os
dataDir = "test1"
for file in os.listdir(dataDir):
print(file)
Summary - relative path
works - in visual studio code
ERROR - macOS terminal python3 /Users/username/Desktop/test/test.py
Traceback (most recent call last):
File "/Users/username/Desktop/test/test.py", line 4, in
for file in os.listdir(dataDir):
FileNotFoundError: [Errno 2] No such file or directory: 'test1'
I all depends on what folder you are in when you launch the code.
Let's say your .py file is in folder1/folder2/file.py and your test1 folder is folder1/folder2/test1/.... You open a terminal in the folder1 and launch python3 /folder2/file.py. The program is going to check for files in folder1/test1/.
Try navigating to the actual file folder, that should work. If you want to use it wherever you launch the code you will have to do some checks on the current directory and manually point the code to the wanted path.
The following solution is inspired by that answer
A simple way to solve your problem is to create the absolute path. (I recommend using that always when you're working with different directories and files)
First of all, you need to care about your actual working directory. While using VS Code your working directory is in your desired directory (/Users/username/Desktop/test/).
But if you use the command line your actual working directory may change, depending where you're calling the script from.
To get the path where script is actually located, you can use the python variable __file__. __file__ is the full path to the directory where your script is located.
To use your script correctly and being able to call it using both ways, the following implementation can help you:
import os
dataDir = "test1"
# absolute path to the directory where your script is in
scriptDir = os.path.dirname(__file__)
# combining the path of your script and the 'searching' directory
absolutePath = os.path.join(scriptDir, dataDir)
for file in os.listdir(absolutePath):
print(file)

Shutil.move doesn't move files

I am trying to move PDF files from one folder to another using shutil.move. After I execute the script, python doesn't see them anymore, while they are still visible in Windows explorer. If I run the script again, python tells me there are no files. I have to run reverse script in order for python to see them. I use 64-bit Python v3.6.4 on Windows 10.
Command prompt with counts
import os, sys
import shutil
from os.path import join
Filez=0
PDFZ=0
filovi = os.listdir("C:/Users/Mirko1/pdfannots-master/NoGo")
for file in filovi:
Filez +=1
if file.endswith(".pdf"):
newdr=join('C:\\', 'Users','Mirko1','pdfannots-master','NoGo', file)
olddr=join('C:\\', 'Users','Mirko1','pdfannots-master', file)
PDFZ +=1
shutil.move(newdr, olddr)
print(Filez)
print(PDFZ)

How do I open a terminal where the python file is executed

I made a script that when clicked on it copies all the files of the directory where it was opened in on to a USB.
It works inside Pycharm but when I convert it to an executable (When I use pyinstaller to convert the .py to a .exec) it does not work.
I’m almost certain I know what’s wrong but I don’t know how to fix it.
import shutil
import os
current = os.getcwd()
list_of_files = os.listdir(current)
def get_files():
print('CURRENT: ' + current)
print('File_List: ' + str(list_of_files))
for files in list_of_files:
shutil.copy(current + '/' + files, '/Volumes/U/Copy_things')
get_files()
Long story short I’m using os.getcwd() so the file knows where it is located.
When I execute the file in Pycharm the current directory that os.getcwd() gives me is
CURRENT: /Users/MainFrame/Desktop/python_test_hub/move_file_test
But when I open the executable (same folder as the .py file ) and the terminal opens up os.getcwd() gives me is
CURRENT: /Users/MainFrame
So I need to find a way for the executable to open up the terminal where it is located so it can copy those files.
I want to be able to execute it from any folder and copy the files to a USB.
os.getcwd() gets the directory of where the script is executed from, and this isn't necessarily where you're script is located. Pycharm is most likely altering this path when executing the script, as it executes your script from the project path, rather than the python path.
Try os.path.abspath(os.path.dirname(os.sys.argv[0])) instead of os.getcwd().
These answers have more information: os.getcwd() vs os.path.abspath(os.path.dirname(__file__))
Difference between __file__ and sys.argv[0]

IOError: [Errno 2] No such file or directory: 'users.txt'

I am getting the above error when I use a webserver to run my code, however locally in the Terminal this works fine. I believe this must be to do with the path to the file working locally but not remotely. I have seen the solution on stackoverflow is to add the filepath like '/user/xxx/library/' etc, however is there a solution that allows this to be system agnostic? As in if I copy this directory to another location/server it will still work?
You can import os, it's built it to Python. You can get teh absolute path of the .py file this way:
import os
ROOT = lambda base : os.path.join(os.path.dirname(__file__), base).replace('\\','/')
Now you can simply do the following:
ROOT('users.txt')
It should return the absolute path.

Categories