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)
Related
I am trying to write a program that will open a file and print its contents. I am having some trouble with defining it I suppose? If it is not telling me that "path" is not defined, then it is telling me that "new_dir" is not defined.
Here is the code:
import pathlib
def prog_info():
print("This program will open a file, read and print its contents.")
print("-----------------------------------------------------------")
prog_info()
file_path = new_dir / "numbers.txt"
file_path.parent.mkdir()
file_path.touch()
with path.open("numbers.txt", mode="r", encoding="utf-8") as file:
for line in file:
print(line.strip())
The file is going to have three numbers that will be printed:
22
14
-99
with open("filename or location", 'r') as my_file:
for line in my_file:
print(line)
I hope this helped you.
You don't need mode, and you don't need the import. All you need is the code provided
I'm trying to use below code to read 5 files from source, write them in destination and then deleting the files in source. I get the following error: [Errno 13] Permission denied: 'c:\\data\\AM\\Desktop\\tester1. The file by the way look like this:
import os
import time
source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'
for file in os.listdir(source):
file_path = os.path.join(source, file)
if not os.path.isfile:
continue
print(file_path)
with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
data ={
'Power': None,
}
for line in IN:
splitter = (ID, Item, Content, Status) = line.strip().split()
if Item in data == "Power":
Content = str(int(Content) * 10)
os.remove(IN)
I have re-written your entire code. I assume you want to update the value of Power by a multiple of 10 and write the updated content into a new file. The below code will do just that.
Your code had multiple issues, first and foremost, most of what you wanted in your head did not get written in the code (like writing into a new file, providing what and where to write, etc.). The original issue of the permission was because you were trying to open a directory to write instead of a file.
source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'
for file in os.listdir(source):
source_file = os.path.join(source, file)
destination_file=os.path.join(destination, file)
if not os.path.isfile:
continue
print(source_file)
with open (source_file, 'r') as IN , open (destination_file, 'w') as OUT:
data={
'Power': None,
}
for line in IN:
splitter = (ID, Item, Content, Status) = line.strip().split()
if Item in data:# == "Power": #Changed
Content = str(int(Content) * 10)
OUT.write(ID+'\t'+Item+'\t'+Content+'\t'+Status+'\n') #Added to write the content into destination file.
else:
OUT.write(line) #Added to write the content into destination file.
os.remove(source_file)
Hope this works for you.
I'm not sure what you're going for here, but here's what I could come up with the question put into the title.
import os
# Takes the text from the old file
with open('old file path.txt', 'r') as f:
text = f.read()
# Takes text from old file and writes it to the new file
with open('new file path.txt', 'w') as f:
f.write(text)
# Removes the old text file
os.remove('old file path.txt')
Sounds from your description like this line fails:
with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
Because of this operation:
open (destination, 'w')
So, you might not have write-access to
c:\data\AM\Desktop\tester1
Set file permission on Windows systems:
https://www.online-tech-tips.com/computer-tips/set-file-folder-permissions-windows/
#Sherin Jayanand
One more question bro, I wanted to try something out with some pieces of your code. I made this of it:
import os
import time
from datetime import datetime
#Make source, destination and archive paths.
source = r'c:\data\AM\Desktop\Source'
destination = r'c:\data\AM\Desktop\Destination'
archive = r'c:\data\AM\Desktop\Archive'
for root, dirs, files in os.walk(source):
for f in files:
pads = (root + '\\' + f)
# print(pads)
for file in os.listdir(source):
dst_path=os.path.join(destination, file)
print(dst_path)
with open(pads, 'r') as IN, open(dst_path, 'w') as OUT:
data={'Power': None,
}
for line in IN:
(ID, Item, Content, Status) = line.strip().split()
if Item in data:
Content = str(int(Content) * 10)
OUT.write(ID+'\t'+Item+'\t'+Content+'\t'+Status+'\n')
else:
OUT.write(line)
But again I received the same error: Permission denied: 'c:\\data\\AM\\Desktop\\Destination\\C'
How comes? Thank you very much!
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.
how do you do this series of actions in python?
1) Create a file if it does not exist and insert a string
2) If the file exists, search if it contains a string
3) If the string does not exist, hang it at the end of the file
I'm currently doing it this way but I'm missing a step
EDIT
with this code every time i call the function seems that the file does not exist and overwrite the older file
def func():
if not os.path.exists(path):
#always take this branch
with open(path, "w") as myfile:
myfile.write(string)
myfile.flush()
myfile.close()
else:
with open(path) as f:
if string in f.read():
print("string found")
else:
with open(path, "a") as f1:
f1.write(string)
f1.flush()
f1.close()
f.close()
Try this:
with open(path, 'a+') as file:
file.seek(0)
content = file.read()
if string not in content:
file.write(string)
seek will move your pointer to the start, and write will move it back to the end.
Edit:
Also, you don't need to check the path.
Example:
>>> f = open('example', 'a+')
>>> f.write('a')
1
>>> f.seek(0)
0
>>> f.read()
'a'
file example didn't exist, but when I called open() it was created. see why
You don't need to reopen the file if you have not yet closed it after initially opening it. Use "a" when opening the file in order to append to it. So... "else: with open(path, "a") as f: f.write(string)". Try that
I want to do some changes in one file. For this purpose I am doing a temporary file where I write content with all wanted changes and at the end I try to replace the original file with this temp one.
Temp file is created and it looks like I expected, but replacing operation do not work.
This is my code which fails:
with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
for line in f:
temp.write(line + " test")
os.replace(temp.name, file_path)
but this gives me an error:
PermissionError: [WinError 32] The process cannot access the file
because it is being used by another process
Is my usage of 'replace' function is wrong?
your command os.replace(temp.name, file_path) has to be out of the with.
with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
for line in f:
temp.write(line + " test")
os.replace(temp.name, file_path)
When you are calling replace() inside 'with' the file is still open as you are still inside the scope of 'with'.
As soon as you're out of 'with' the file has now been closed and you can now replace with os.replace().
Try it.
with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
for line in f:
temp.write(line + " test")
os.replace(temp.name, file_path)