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.
Related
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.
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
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
This is the error I get when I try reading in the file.
logfile = open(r'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.txt')
IOError: [Errno 2] No such file or directory: 'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.txt'
logfile = open(r'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.log')
with open(logfile, 'r') as read:
TypeError: coercing to Unicode: need string or buffer, file found
As you can see, when I try to read as a txt file it doesn't recognize the file. When I try to read as a log file it finds the file but generates an error.
Any suggestions on how to read this file in. It's a simple text file with rows like this
[02/Jan/2015:08:07:32] "GET /click?article_id=162&user_id=5475 HTTP/1.1" 200 4352
I've already tried changing the name of file to txt and that doesn't work.
Error one: the File
r'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.txt'
does not exist.
Error two:
The file
'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.log'
does exist but the function open(...) expects a string that is the full path to the file. In the line with open(logfile, 'r') as read: the variable logfile is already a file-object, not a string anymore.
Try the following:
logFilePath = r'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.log'
with open(logFilePath, 'r') as fileObject:
pass # do the stuff you want with the file
# When you leave this indentation, the file object will be closed again
I am trying to read the log files or any other file and display in web browser using django and python
I used this code
data_file = open('/var/log/samba', 'r') # note -- 'r' not r
data = data_file.readlines() # returns a list of lines
I get this error
[Errno 21] Is a directory: '/var/log/samba'
You're trying to open a directory. Don't do that. Open a file instead.