Access html file in write mode using python - 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.

Related

Opening Test File on Cisco IOSXE python guestshell

I successfully transferred a text file (zero_conf.txt) to a Cisco IOSXE (Amsterdam) switch flash file system using python on the guestshell.
However when I try to open the text file using the following code:
with open('/flash/zero_conf.txt','r+') as f:
lines = f.readlines()
I am getting the following error:
with open('/flash/zero_conf.txt','r+') as f:
FileNotFoundError: [Errno 2] No such file or directory: '/flash/zero_conf.txt'
Please let me know if I am making a syntax error or what will be the correct way to open a text file on the Cisco iosxe python guestshell.

error reading and writing files in cloud function

I am reading file from SharePoint and writitng in GCS bucket but when I run the function it gives me error "Error [Errno 30] Read-only file system: 'test.xlsx'"
here is the code
response = File.open_binary(ctx,location/file )
blob = bucket.blob('/sharepoint/' + doc)
print('connection')
with open("test.xlsx", "wb") as local_file:
blob.upload_from_file(local_file)
local_file.close()
please help if anyone know the solution of this error
Doing this open("test.xlsx", "wb") destroys the file. The file is also locked while open which causes the error message.
Change your code to open the file in read mode:
with open("test.xlsx", "rb") as local_file:
blob.upload_from_file(local_file)
local_file.close()

Why I get PermissionError if file is closed? (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.

Why a new NamedTemporaryFile object has a path, but a file is not available? [duplicate]

I am attempting to create and write to a temporary file on Windows OS using Python. I have used the Python module tempfile to create a temporary file.
But when I go to write that temporary file I get an error Permission Denied. Am I not allowed to write to temporary files?! Am I doing something wrong? If I want to create and write to a temporary file how should should I do it in Python? I want to create a temporary file in the temp directory for security purposes and not locally (in the dir the .exe is executing).
IOError: [Errno 13] Permission denied: 'c:\\users\\blah~1\\appdata\\local\\temp\\tmpiwz8qw'
temp = tempfile.NamedTemporaryFile().name
f = open(temp, 'w') # error occurs on this line
NamedTemporaryFile actually creates and opens the file for you, there's no need for you to open it again for writing.
In fact, the Python docs state:
Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
That's why you're getting your permission error. What you're probably after is something like:
f = tempfile.NamedTemporaryFile(mode='w') # open file
temp = f.name # get name (if needed)
Use the delete parameter as below:
tmpf = NamedTemporaryFile(delete=False)
But then you need to manually delete the temporary file once you are done with it.
tmpf.close()
os.unlink(tmpf.name)
Reference for bug: https://github.com/bravoserver/bravo/issues/111
regards,
Vidyesh
Consider using os.path.join(tempfile.gettempdir(), os.urandom(24).hex()) instead. It's reliable, cross-platform, and the only caveat is that it doesn't work on FAT partitions.
NamedTemporaryFile has a number of issues, not the least of which is that it can fail to create files because of a permission error, fail to detect the permission error, and then loop millions of times, hanging your program and your filesystem.
The following custom implementation of named temporary file is expanded on the original answer by Erik Aronesty:
import os
import tempfile
class CustomNamedTemporaryFile:
"""
This custom implementation is needed because of the following limitation of tempfile.NamedTemporaryFile:
> Whether the name can be used to open the file a second time, while the named temporary file is still open,
> varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
"""
def __init__(self, mode='wb', delete=True):
self._mode = mode
self._delete = delete
def __enter__(self):
# Generate a random temporary file name
file_name = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
# Ensure the file is created
open(file_name, "x").close()
# Open the file in the given mode
self._tempFile = open(file_name, self._mode)
return self._tempFile
def __exit__(self, exc_type, exc_val, exc_tb):
self._tempFile.close()
if self._delete:
os.remove(self._tempFile.name)
This issue might be more complex than many of you think. Anyway this was my solution:
Make use of atexit module
def delete_files(files):
for file in files:
file.close()
os.unlink(file.name)
Make NamedTemporaryFile delete=False
temp_files = []
result_file = NamedTemporaryFile(dir=tmp_path(), suffix=".xlsx", delete=False)
self.temp_files.append(result_file)
Register delete_files as a clean up function
atexit.register(delete_files, temp_files)
tempfile.NamedTemporaryFile() :
It creates and opens a temporary file for you.
f = open(temp, 'w') :
You are again going to open the file which is already open and that's why you are getting Permission Denied error.
If you really wants to open the file again then you first need to close it which will look something like this-
temp= tempfile.NamedTemporaryFile()
temp.close()
f = open(temp.name, 'w')
Permission was denied because the file is Open during line 2 of your code.
close it with f.close() first then you can start writing on your tempfile

Notepad++ script permission denied to text file

I'm trying to scrape some information and then add it to a text file but when I run the script, I get the following error:
PermissionError: [Errno 13] Permission denied: 'stocks.txt'
I'm doing this for adding to the file.
f = open("stocks.txt", "a")
f.write(containers[0].string + "\n")
f.close()
When I go to my file explorer and right click the program and press run, it prints to the file but any other way gives me the error.

Categories