I am trying to make a program that needs to read and write some information from certain files. This is done multiple times over and over again as the program continues. The program can open the files as normal without issues in the beginning, but after a while the program crashes with the error:
PermissionError: [Errno 13] Permission denied: 'Player_1.json'
The code that reads the file:
def json_read(json_file):
with open(json_file, 'r+', encoding='utf-8') as file:
root = json.load(file)
file.close()
return root[0]["Player_Cards"]
The code that writes to the file:
def json_write(json_file, write):
with open(json_file, 'r+') as file:
data = json.load(file)
file.close()
data[0]["Player_Cards"] = write
with open(json_file, 'w+') as file:
json.dump(data, file)
file.close()
From what I have heard from other sources, it might be an OS error that limits the amount of times a file can be opened in a timespan. If that is the case how do I fix that error?
Edit:
I am using Windows 10.
Related
What I need to do is to write some messages on a .txt file, close it and send it to a server. This happens in a infinite loop, so the code should look more or less like this:
from requests_toolbelt.multipart.encoder import MultipartEncoder
num = 0
while True:
num += 1
filename = f"example{num}.txt"
with open(filename, "w") as f:
f.write("Hello")
f.close()
mp_encoder = MultipartEncoder(
fields={
'file': ("file", open(filename, 'rb'), 'text/plain')
}
)
r = requests.post("my_url/save_file", data=mp_encoder, headers=my_headers)
time.sleep(10)
The post works if the file is created manually inside my working directory, but if I try to create it and write on it through code, I receive this response message:
500 - Internal Server Error
System.IO.IOException: Unexpected end of Stream, the content may have already been read by another component.
I don't see the file appearing in the project window of PyCharm...I even used time.sleep(10) because at first, I thought it could be a time-related problem, but I didn't solve the problem. In fact, the file appears in my working directory only when I stop the code, so it seems the file is held by the program even after I explicitly called f.close(): I know the with function should take care of closing files, but it didn't look like that so I tried to add a close() to understand if that was the problem (spoiler: it was not)
I solved the problem by using another file
with open(filename, "r") as firstfile, open("new.txt", "a+") as secondfile:
secondfile.write(firstfile.read())
with open(filename, 'w'):
pass
r = requests.post("my_url/save_file", data=mp_encoder, headers=my_headers)
if r.status_code == requests.codes.ok:
os.remove("new.txt")
else:
print("File not saved")
I make a copy of the file, empty the original file to save space and send the copy to the server (and then delete the copy). Looks like the problem was that the original file was held open by the Python logging module
Firstly, can you change open(f, 'rb') to open("example.txt", 'rb'). In open, you should be passing file name not a closed file pointer.
Also, you can use os.path.abspath to show the location to know where file is written.
import os
os.path.abspath('.')
Third point, when you are using with context manager to open a file, you don't close the file. The context manger supposed to do it.
with open("example.txt", "w") as f:
f.write("Hello")
this is my code to open a file and get the text from it :
f = open("C:/Users/muthaharsh/Documents/Harsh/News
Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-
Mint.txt","r+")
text = f.readlines()
print(text)
but i keep getting the error :
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt'
What code do i write to be able to do this ?
Thanks in advance ...
It's the whitespace in the path to file. Either use
r"C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt"
or remove the whitespace in the filepath.
If you are running the code on windows add r before your filepath string.
Another way is that you can provide your input file as system arguments.
import sys
file_name = sys.argv[1]
with open(file_name, 'r') as f1:
file_text = f1.read()
print(file_text)
eg: python program for reading the file
you can run the code considering script is saved as readFile.py:
D:\Programs>python readFile.py D:\test.txt
output: This is a sample file
Here is the text
Using python, I am trying to edit the hosts file.
with open('C:\Windows\System32\drivers\etc\hosts', 'r+') as file:
data = file.readlines()
data[70] = '127.0.0.1 web.alanmrsa.com'
file.writelines(data)
print('done')
When I run this file, it gives me the following error:
PermissionError: [Errno 13] in python
C:\Windows\System32\drivers\etc\hosts is writable only by Administrator. You should run your script as Administrator instead.
Also note that you should do a file.seek(0) after data = file.readlines() so that you can overwrite the original content, and also do a file.truncate() after file.writelines(data) so that there would be no leftover characters from the original content in case your replacement string is shorter than the content of the original 71th line.
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
I am reading from a file, adding a line to it and then saving it back.
In C# this would work - But not in Python. Can anyone tell me why?
f = "blogs/%s.comment" % blogtitle
if os.path.isfile(f):
temp = file(f).readlines()
temp.append(comment)
overr = open(f, "w") #line 13
for l in temp: overr.write(l)
The error I get is IOError: [Errno 13] Permission denied at line 13
I am running this file as a .wsgi in Apache and have 775 permissions in the folder where the file is stored.
You forgot to close the file after you had opened it the first time, do it as follows:
f = "blogs/%s.comment" % blogtitle
if os.path.isfile(f):
with open(f, 'r') as fl:
temp = fl.readlines()
temp.append(comment)
with open(f, "w") as fl:
for l in temp: fl.write(l)
You didn't close the file. You should open the file in a with statement to handle closing. Also, it's simpler and more efficient to just open the file in append mode instead of reading the whole thing and writing it back:
path = "blogs/%s.comment" % blogtitle
with open(path, 'a') as f:
f.write(comment)