Why I get PermissionError if file is closed? (Python) - python

I get this error while I'm running my code:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: error
but my file is closed, can you please help?
def delete_employee(self, new_employee):
employees_csv_data = self.open_and_read_file(self.list_of_employees)
with open(EMPLOYEES_EDIT_FILE, 'w') as updated_csv:
writer = csv.writer(updated_csv)
if str(new_employee.employee_id) not in str(employees_csv_data.values):
print(EMPLOYEE_DOESNT_EXIST_IN_FILE_MSG)
else:
for row in employees_csv_data.values:
if new_employee.employee_id != str(row[0]):
writer.writerow(row)
os.rename(EMPLOYEES_EDIT_FILE, self.list_of_employees)
os.remove(self.list_of_employees)

Looks like some other application is accessing this file. Try to delete it and create it again or restart the system.

Related

Getting Python error -->PermissionError: [WinError 32] The process cannot access the file because it is being used by another process

I'm trying to read a csv file from local path using python & then I process the records of csv file into json structure , finally printing them on console. I have written the code within try & except block.I'm expecting that if any exception happens in the try block while reading the data from csv file, the except block should print that exception has occured & it should move the csv file from current location to folder called errored. But while testing via simulating the errored scenario ,it is unable to move the csv in errored folder.Instead it throws error:- "PermissionError: [WinError 32] The process cannot access the file because it is being used by another process".Below is the code:-
try:
global df
df = pd.read_csv('CBD_BU_FULL.csv', encoding='UTF-8', dtype=str)
df = df.assign(FILE_TYPE ='BU')
data = df.to_json(orient = "records", lines=False).split('\n')
print(data)
except:
print("An exception occurred")
os.rename('CBD_BU_FULL.csv', '/Errored/CBD_BU_FULL.csv')
It's quite possible that pd.read_csv isn't properly closing the file since it is crashing mid read, I would try opening the file yourself so that in the except your own program is definitely closing the file and this may fix your issue.
import traceback
import pandas as pd
try:
with open('CBD_BU_FULL.csv', "r") as f:
df = pd.read_csv(f, encoding='UTF-8', dtype=str)
df = df.assign(FILE_TYPE ='BU')
data = df.to_json(orient = "records", lines=False).split('\n')
print(data)
except:
traceback.print_exc(1)
os.rename('CBD_BU_FULL.csv', '/Errored/CBD_BU_FULL.csv')
You cannot use os.rename if the file is in use. You could use shutil.copy instead.

Python PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: mp4 file

Im currently getting this error
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'smallvideos/file1.mp4'
I have tried different ways to close the file but without luck, no idea what I'm doing wrong here.
def create_file(today):
list_of_clips = []
with open("video_names.txt") as clip_file:
read_file = clip_file.read()
lines = read_file.splitlines()
clip_file = open("video_names.txt")
for line in lines:
#Creates video in 720p - keeps original aspect ratio
video = VideoFileClip(line, target_resolution=(720, None))
list_of_clips.append(video)
os.remove(line)
filename = "combinedVideo_" + str(today) + ".mp4"
final_clip = concatenate_videoclips(list_of_clips, method='compose')
final_clip.write_videofile(filename)
return filename
This is basically permission error, you just need to close the file before removing it. After getting the file size info.
clip_file.close()

Errno 13 Permission denied.... I can't access this JSON file

I am trying to open a JSON file.
Here is my code:
import json
fh = open('C:/Users/Joker/Desktop/Python/Code3/roster')
data = json.loads(fh)
for i in data:
print(i)
However, I keep getting the error:
Traceback (most recent call last):
File "C:\Users\Joker\Desktop\Python\jsondatabase.py", line 3, in <module>
fh = open('C:/Users/Joker/Desktop/Python/Code3/roster')
PermissionError: [Errno 13] Permission denied: 'C:/Users/Joker/Desktop/Python/Code3/roster'
[Finished in 0.135s]
How can I access the data?
Edit: It worked when I ran as admin. Thanks everyone!
The code as written orphans the file handler, leaving it open. It may very well be open in another program which is hard to see from the process manager, but you should edit to:
import json
with open('C:/Users/Joker/Desktop/Python/Code3/roster.json', "r") as fh:
data = json.load(fh)
for i in data:
print(i)
To clear the orphaned handler you could try wack-a-mole with the task manager or just restart your machine.

Close already open csv in Python

Is there a way for Python to close that the file is already open file.
Or at the very least display a popup that file is open or a custom written error message popup for permission error.
As to avoid:
PermissionError: [Errno 13] Permission denied: 'C:\\zf.csv'
I've seen a lot of solutions that open a file then close it through python. But in my case. Lets say I left my csv open and then tried to run the job.
How can I make it so it closes the currently opened csv?
I've tried the below variations but none seem to work as they expect that I have already opened the csv at an earlier point through python. I suspect I'm over complicating this.
f = 'C:\\zf.csv'
file.close()
AttributeError: 'str' object has no attribute 'close'
This gives an error as there is no reference to opening of file but simply strings.
Or even..
theFile = open(f)
file_content = theFile.read()
# do whatever you need to do
theFile.close()
As well as:
fileobj=open('C:\\zf.csv',"wb+")
if not fileobj.closed:
print("file is already opened")
How do I close an already open csv?
The only workaround I can think of would be to add a messagebox, though I can't seem to get it to detect the file.
filename = "C:\\zf.csv"
if not os.access(filename, os.W_OK):
print("Write access not permitted on %s" % filename)
messagebox.showinfo("Title", "Close your CSV")
Try using a with context, which will manage the close (__exit__) operation smoothly at the end of the context:
with open(...) as theFile:
file_content = theFile.read()
You can also try to copy the file to a temporary file, and open/close/remove it at will. It requires that you have read access to the original, though.
In this example I have a file "test.txt" that is write-only (chmod 444) and it throws a "Permission denied" error if I try writing to it directly. I copy it to a temporary file that has "777" rights so that I can do what I want with it:
import tempfile, shutil, os
def create_temporary_copy(path):
temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, 'temp_file_name')
os.chmod(temp_path, 0o777); # give full access to the tempfile so we can copy
shutil.copy2(path, temp_path) # copy the original into the temp one
os.chmod(temp_path, 0o777); # replace permissions from the original file
return temp_path
path = "./test.txt" # original file
copy_path = create_temporary_copy(path) # temp copy
with open(copy_path, "w") as g: # can do what I want with it
g.write("TEST\n")
f = open("C:/Users/amol/Downloads/result.csv", "r")
print(f.readlines()) #just to check file is open
f.close()
# here you can add above print statement to check if file is closed or not. I am using python 3.5

Access html file in write mode using python

example.py
file = open("innovative.html", "w")
file.write("This is a test\n")
file.write("And here is another line\n")
file.close()
return render_template('innovative.html')
while I am executing this file in server it throwing [Errno 13] Permission denied: 'innovative.html'
I am executing this file in rhcloud.
I changed permissions for file as -rwx- for innovative.html
Thanks in advance.
This error can occur when a file is actively opened or utilized by another process at the same time (as well as when permissions are not given). Be sure to check that the file is not being used while attempting to write.

Categories