I know there are few threads already for the problem, but I couldnt resolve my problem. Any help will be appreciated.
I have set of files which has be replaced by the starting word.But I get this error everytime I use os.rename().I even tried using shutil.move().But it does not work
for f in os.listdir(p):
path, filename = os.path.split(f)
file_name, file_ext = os.path.splitext(f)
start, *rest = file_name.rsplit("_",1)
new_filename = '_'.join(start.split('_')[:-3])
#print(new_filename)
old_file = os.path.join(path,file_name)
new_file = os.path.join(path,new_filename)
#print(old_file)
print(new_file)
try:
os.rename(old_file, new_file)
except WindowsError:
os.remove(new_file)
os.rename(old_file, new_file)
FileNotFoundError: [WinError 2] The system cannot find the specified file: '1212_seg01_src13_cam01_meas' -> '1212'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/temp/mptAlgorithm2dPython_vc141_0.0.1_mtu/datapreprocessing.py", line 23, in <module>
os.remove(new_file)
PermissionError: [WinError 5] Access denied: '1212'
Related
Hi i tried to move some local files to a nas but it raises an Access is denied error. I have compiled the script to .exe file with auto-py-to-exe. I tried to set some rights to the local folder but it didn't work. Run the script with adminrights but now i haven't rights on the nas, the rights on the nas i can't change.
python script:
import os, shutil, time, logging, stat
logging.basicConfig(filename="test.log", format='%(asctime)s %(message)s\n', encoding='utf-8')
try:
start = int(input("Startdate: "))
end = int(input("Enddate: "))
filePath = "D:/path/to/file"
storePath = "Z:"
count= 0
for file in os.listdir(filePath):
fname = int(file.split("_")[0])
if fname >= start and fname <= end:
count += 1
print(f"You are about to move {count} folder from {filePath} to {storePath}!")
answer = input("Do you want to move these files?(y/n): ")
if answer != "y":
print("Cancelled!")
exit()
for file in os.listdir(filePath):
fname = int(file.split("_")[0])
if fname >= start and fname <= end:
try:
os.chmod(f"{filePath}/{file}", stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
except:
logging.log(f"\nRights were not changed for\n{filePath}/{file}\n\n")
shutil.move(f"{filePath}/{file}", f"{storePath}/{file}")
print(f"{filePath}/{file} moved to {storePath}/{file}")
time.sleep(60)
except Exception as e:
logging.exception(e, exc_info=True)
logfile:
2022-11-15 16:03:25,839 [WinError 5] Access is denied: 'D:/path/to/file/20211124_1_6377401797037988\\20211124.txt'
Traceback (most recent call last):
File "shutil.py", line 824, in move
OSError: [WinError 17] The system cannot move the file to a different disk drive: 'D:/path/to/file/20211124_1_6377401797037988' -> 'Z:/20211124_1_6377401797037988'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 39, in <module>
File "shutil.py", line 842, in move
File "shutil.py", line 758, in rmtree
File "shutil.py", line 621, in _rmtree_unsafe
File "shutil.py", line 619, in _rmtree_unsafe
PermissionError: [WinError 5] Access is denied: 'D:/path/to/file/20211124_1_6377401797037988\\20211124.txt'
Your path to file flips the '/' to '\' at the filename. You can use 'r' in front of file names to ensure the slashes are maintained
https://docs.python.org/3/reference/lexical_analysis.html#:~:text=Both%20string%20and,is%20not%20supported.
I have no idea why this error message is coming up... is there something wrong with my file path? Am I using os incorrectly?
any help is much appreciated!
def save_hotel_info_file(self):
hotel_name = self.name
new_hotel = (hotel_name.replace(' ', '_')).lower()
path = 'hotels/' + hotel_name
os.makedirs(path)
fobj = open('hotel_info.txt', 'w', encoding='utf-8')
fobj.write(self.name + '\n')
for room_obj in self.rooms:
room_str = 'Room ' + str(room_obj.room_num) + ',' + room_obj.room_type + ',' + str(room_obj.price)
fobj.write(room_str + '\n')
fobj.close()
```
Traceback (most recent call last):
File "/Users/myname/Documents/hotel.py", line 136, in <module>
h.save_hotel_info_file()
File "/Users/myname/Documents/hotel.py", line 120, in save_hotel_info_file
os.makedirs(path)
File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/../../../../../../../Python.framework/Versions/3.7/lib/python3.7/os.py", line 223, in makedirs
mkdir(name, mode)
FileExistsError: [Errno 17] File exists: 'hotels/Queen Elizabeth Hotel'
The exception is thrown from mkdirs if the dir you're trying to create already exists. Its ment to notify you of that fact.
You should catch the specific exception like so:
try:
os.makedirs(path)
except FileExistsError:
# the dir already exists
# put code handing this case here
pass
Since python 3.4.1 you can use this optional parameter to disable the exception if you dont care weather the dir exists already or not.
os.makedirs(path, exist_ok=True)
I am trying to run the code below in order to extract zip files from a folder and its subfolders to another folder. I have a script that extracts my files correctly but not the ones under the subfolder. I asked the question here and been redirected to an answer from SO that I'll be adding below. People are saying it's working for them but it's giving me an error:
Traceback (most recent call last):
File "C:/Users/BerkayTok/PycharmProjects/GeoPandas/MergeAnswer3.py", line 7, in <module>
zip_file = zipfile.ZipFile(my_zip, 'r')
File "C:\Users\username\Anaconda3\envs\playground\lib\zipfile.py", line 1207, in __init__
self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\username\\My_Dataset
What can I try to manage this error?
import shutil
import zipfile
my_dir = r"D:\Download"
my_zip = r"D:\Download\my_file.zip"
with zipfile.ZipFile(my_zip) as zip_file:
for member in zip_file.namelist():
filename = os.path.basename(member)
# skip directories
if not filename:
continue
# copy file (taken from zipfile's extract)
source = zip_file.open(member)
target = open(os.path.join(my_dir, filename), "wb")
with source, target:
shutil.copyfileobj(source, target)
I'm copying a file to the temp dir
def uploadAvatar(self, schid, img):
try:
img = path.abspath(img)
filename = self.generateAvatarFileName(schid)
temp_dir = tempfile.gettempdir()
self.tmp = path.join(temp_dir, filename)
copy2(img, self.tmp)
#imgname = path.basename(self.tmp)
imgdir = path.dirname(self.tmp)+path.sep
self.retcode = ts3lib.createReturnCode()
(error, ftid) = ts3lib.sendFile(schid, 0, "", "/avatar/"+filename, True, False, imgdir, self.retcode);
except:
try: from traceback import format_exc;ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon Script", 0)
except:
try: from traceback import format_exc;print(format_exc())
except: print("Unknown Error")
and want to delete it after I uploaded it
def onServerErrorEvent(self, schid, errorMessage, error, returnCode, extraMessage):
if self.retcode == returnCode: self.setAvatar(schid, self.tmp);remove(self.tmp)
But I always get
Error calling method of plugin Dynamic Avatar Changer: Traceback (most recent call last):
File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\ts3plugin.py", line 259, in callMethod
ret.append(meth(*args))
File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\dynamicAvatar\__init__.py", line 114, in onServerErrorEvent
if self.retcode == returnCode: self.setAvatar(schid, self.tmp);remove(self.tmp)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\blusc\\AppData\\Local\\Temp\\avatar_ZFV2RGU5MjNmb0NyN3hsN1NnU3BGQzdsTFZZPQ'
How can accomplish this? Please help!
Sounds like you need to close the file or stop the process heres a link I found that my be able to solve your problem. File handling in Python - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process.
Why am I getting
Traceback (most recent call last): File "C:\temp\py\tesst.py", line 8, in <module>
os.remove( PATH ) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:
'C:\temp\py\test.txt'
import os
PATH = r'C:\temp\py\test.txt'
f = open ( PATH,'w')
f.write('test\n')
f.close;
os.remove( PATH )
Am I missing something?
You are calling f.close instead of f.close(). It would be better to open the file contextually so it will be closed automatically.
import os
PATH = r'C:\temp\py\test.txt'
with open(PATH, 'wb') as f:
f.write('test\n')
os.remove(PATH)