Is there a way to write to a read-only file in Python? I am trying to write a script which helps me add debug statements at the start of every function in a given file. But the issue I have is that before I run the script, I have to manually remove the read-only flag on the file. is there anyway I can write to read-only files without manually having to remove them? Any suggestions will be deeply appreciated. Thanks.
If the user that runs the script doesn't have permissions to write in a file, you can't edit it. Basically, you need to have the w permission to edit a file. See Linux file permissions for more information.
If you want to get rid of it, you should make the file writable directly, or try to change its chmod with the os module, if you have enough permission to do this:
>>> os.chmod('path_to/file', 0755)
Try os.chmod() before opening the file.
Related
I'm trying to restrict write and read access to a Python file. Suppose I have the following code:
with open('test.py', 'w+') as file:
file.write('''
open("document.txt", "w+").write("Hello, World!")
open("document.txt", "r+").read()
''')
By executing this code, a new file is created that in the new file there are two lines of code to write and read a another file.
I want the file created by executing this code (test.py) to hit PermissionError while running and not be able to create a new file or read it; Also, this file is only executable and normal commands work in it, but it can not access other files.
If I read you correctly, this is not a python problem, but an environment problem. I understand the question as something like 'how do I prevent python code from executing arbitrary reads or writes?'. There would be a trivial solution (modifying the generated test.py so it throws an error) but presumably that's not what you want.
The easiest way to make python hit a PermissionError... is to make sure it doesn't have permissions. So run your code as a user with extremely limited permissions---specifically no write permissions anywhere---or perhaps no default permissions at all, and use something like facls to grant permission to read specific files explicitly from a more priveleged sentinel process. (This assumes you are running Linux, but there are likely other ways to do this in different OSs).
Alternatively, look into various sandboxing techniques to give you a python interpreter with the relavent modules replaced with modules which throw errors, or an environment where outside modification is impossible.
It would help if you made it clearer why this is important, and why you are writing a python script with another python script (is this just an example of malicious action?).
You could technically change the permission of the file itself on the filesystem your trying to access.
Check the previous thread about changing permissions
os.chmod(path, <permission value>)
Where 000 is to disable anyone other than root to edit on linux.
I want to change a file to be permanently read-only and tried the solutions provided creating-read-only-pdf-file-using-python and change-file-to-read-only-mode-in-python.
However, in both cases it was still possible to edit the file and manually change it back to a read-only file.
Is there a way to prevent that, so that nobody could edit the properties or content of the file?
I thought about encrypting it, i.e. using SHA256 with a randomly created key, but that would render the file unreadable.
Is there a way to prevent that, so that nobody could edit the properties or content of the file?
No. As long as the file is on a writable device, it's always possible for a user to delete the file and replace it with a modified copy.
(And even if the file is on an immutable device, like a CD-ROM, the user can still create a modified copy of the entire device.)
If you are one a Unix-like system you can use the chmod command in the terminal.
The chmod command has an equivalent in python
You might have to run your script is super-user to change some permissions.
my program creates a log file on the users desktop using:
file = open(os.path.expanduser("~/Desktop/Log.txt"), 'a')
But later I need to send the log file back to myself using MIME. To send a file it needs the the file directory but I do not know how to find that? I tried doing this:
filename='(os.path.expanduser("~/Desktop/Log.txt"), 'a')'
But this does not work. Is there another way to do this? If there is then please give an example since I am a beginner and don't really know what im doing.
Did you try this one? See if it works.
directory=os.path.dirname(os.path.expanduser("~/Desktop/Log.txt"))
if you want absolute path try
fullpath=os.path.abspath(os.path.expanduser("~/Desktop/Log.txt"))
more convenient functions here:
https://docs.python.org/3/library/os.path.html
I have a simple web-server written using Python Twisted. Users can log in and use it to generate certain reports (pdf-format), specific to that user. The report is made by having a .tex template file where I replace certain content depending on user, including embedding user-specific graphs (.png or similar), then use the command line program pdflatex to generate the pdf.
Currently the graphs are saved in a tmp folder, and that path is then put into the .tex template before calling pdflatex. But this probably opens up a whole pile of problems when the number of users increases, so I want to use temporary files (tempfile module) instead of a real tmp folder. Is there any way I can make pdflatex see these temporary files? Or am I doing this the wrong way?
without any code it's hard to tell you how, but
Is there any way I can make pdflatex see these temporary files?
yes you can print the path to the temporary file by using a named temporary file:
>>> with tempfile.NamedTemporaryFile() as temp:
... print temp.name
...
/tmp/tmp7gjBHU
As commented you can use tempfile.NamedTemporaryFile. The problem is that this will be deleted once it is closed. That means you have to run pdflatex while the file is still referenced within python.
As an alternative way you could just save the picture with a randomly generated name. The tempfile is designed to allow you to create temporary files on various platforms in a consistent way. This is not what you need, since you'll always run the script on the same webserver I guess.
You could generate random file names using the uuid module:
import uuid
for i in xrange(3):
print(str(uuid.uuid4()))
The you save the pictures explictly using the random name and pass insert it into the tex-file.
After running pdflatex you explicitly have to delete the file, which is the drawback of that approach.
I have a dataframe that I want to export to Excel. I'm new to python and pandas so I need some help on this simple task.
df2.to_excel('C:\BT\stack_test3.xlsx')
Error message:
IOError: [Errno 13] Permission denied: 'C:\BT\stack_test3.xlsx'
You path is incorrect, because you have not escaped the slashes it thinks you are trying to write to the root of c: drive use the following:
df2.to_excel(r'C:\BT\stack_test3.xlsx')
The r makes the path a raw string and means you do not need to escape the slashes
Edit
It seems that there is some error with openpyxl as using
df2.to_excel(r'C:\BT\stack_test3.xls')
works which uses xlwt, I don't know enough about those packages so it could be either a permissions problem with openpyxl which I have not been able to find anything about or a bug.
I had an identical problem. Turns out it's because I had left the Excel file open whilst I was trying to write to it. Apparently it doesn't like that. If you have it open try closing it.
To confirm...in case future readers stumble in this page...before complicating things make sure that the excel file you are trying to save is not already open or to be safe.
Just close all of excel and try save it again.
That should do it.
You should write to another drive like 'D:' because in Windows Vista or above that you have no permission to write to 'C:\' and you have no reason to earn the permission.
After closing all instances of excel and running
python code works.