How to write to a file which is open? - python

I am writing my script's output to an Excel file using openpyxl, which is working fine. However, if the Excel file is accidently open while Python is trying to write to it, it shows a PermissionError- which is expected. On this case, what I would have preferred is to write somehow rather than showing the error. Is there a way to do this?

You can't really solve this because the problem is not with openpyxl per-se, rather with the file you manually opened. If you would have opened it as a Read-Only file, you will not get that error. Of course, you can't (easily) solve that programmatically as openpyxl is not aware of the open instances of Excel you have running in the background.
Note that when opening the file as read-only, you will not see the saved changes from openpyxl.
One possible workaround, to avoid losing your changes you were about to save, is to allow the user to close that instance of Excel and try to save again. Something like:
while True:
try:
wb.save(path)
except PermissionError:
input(f"Please close the excel {path} and press Enter")
else:
print(f"Excel file saved successfully at - {path}")
break
Alternatively save to a temporary file and let the user merge later:
from pathlib import Path
try:
wb.save(path)
except PermissionError:
path = Path(path)
temp_path = path.with_name(f"{path.stem}_temp{path.suffix}")
wb.save(temp_path)
print(f"Excel file saved temporarily at - {temp_path}")
else:
print(f"Excel file saved successfully at - {path}")
Warning: these might cover-up other possible PermissionErrors, so use with care.

Related

Need help to open a file in python

I don't know what's wrong here, all I'm trying to do is to open this file, but it says it can't find such a file or directory, however as I have highlighted on the side, the file is right there. I just want to open it. I have opened files before but never encountered this. I must have missed something, I checked online, and seems like my syntax is correct, but I don't know.
I get the same error when I try with "alphabetical_words" which is just a text file.
When open() function receives a relative path, it looks for that file relative to the current working directory. In other words: relative to the current directory from where the script is run. This can be any arbitrary location.
I guess what you want to do is look for alphabetical.csv file relative to the script location. To do that use the following formula:
from pathlib import Path
# Get directory of this script
THIS_DIR = Path(__file__).absolute().parent
# Get path of CSV file relative to the directory of this script
CSV_PATH = THIS_DIR.joinpath("alphabetical.csv")
# Open the CSV file using a with-block
with CSV_PATH.open(encoding="utf-8") as csvfile:
pass # Do stuff with opened file
You need to import csv. Then you can open the file as a csv file. For example,
with open ("alphabetical.csv", "r") as csvfile:
Then you can use the file.
Make sure the file is in your cwd.

The file is used by another process error followed by unexpected behaviour

I'm trying to create a .txt file and move it to a specified folder using the code below, but I get PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\Emre\Desktop\testbot\asdf\testuser.txt'
this error which is followed by the script creating a txt file in both the directory the script is running and the directory I wanted shutil to move the txt file to. What should I do? Thanks in advance.
import shutil
file = open("{}.txt".format(source), "w")
file.write("username = {}\n".format(source))
file.write("user_points = 200\n")
file.close
shutil.move("C:\\Users\\Emre\\Desktop\\testbot\\asdf\\{}.txt".format(source), "C:\\Users\\Emre\\Desktop\\testbot\\asdf\\users")
self.bot.say(channel, "You have been successfully registered, {}!".format(source))
Your code says
file.close
when it should say
file.close()
Since you are just "mentioning" the close method rather than actually calling it, the file is not getting closed. And because it is still open, you will not be able to move it.
Note that the best practice for opening files is to use a context manager:
with open("{}.txt".format(source), "w") as file:
file.write("username = {}\n".format(source))
file.write("user_points = 200\n")
shutil.move( ...
Then the file will get automatically closed when you exit the with clause for any reason—so you don't need to worry about closing it explicitly, even if you want to return early or raise an exception.

Python deleting temporary files on trinket.io

I'm really new to coding sorry if my questions sound stupid. I've created a program and I need it to delete any temporary files created during runtime.
So far the first error I've stumbled upon is insufficient permissions to delete a folder, hence the try-except for PermissionError.Secondly I need to upload this to a trinket.io link to test it and send it to be graded but nothing seems to be deleted there and no permission errors either? Seems like the whole function is getting skipped. Here is what i have so far on the file-deleting function. It keeps only the 4 necessary files...
def clear_temps():
c=os.getcwd()
d=os.listdir(c)
for file in d:
if '.py' in file or '.csv' in file and not file=='mytemp.csv':
pass
else:
if os.path.isdir(file):
os.path.split(file)
try:
os.remove(file)
except PermissionError:
pass
The code you wrote should work fine. Try it in a local Python editor to check it for sure.
I have noticed that in trinket when you delete a file the tab is not removed, but if you check in the folder the file is not there.
You can use this code to check out if the file is still there:
def clear_temps():
c=os.getcwd()
d=os.listdir(c)
for file in d:
if '.py' in file or '.csv' in file and not file=='mytemp.csv':
pass
else:
if os.path.isdir(file):
os.path.split(file)
try:
print(os.path.isfile(file))
os.remove(file)
print(os.path.isfile(file))
except PermissionError:
pass
I added an check if the file exists before and after the remove.
So in case of an output : True False the file in trinket has been really deleted and in case of an True True the file is still there.

Close a file from within python

I have a py script that runs every night collecting data from an api and updating a number of csv files (using pandas .to_csv. Sometimes one of the files might be open in excel (because I've been looking at it and forgot to close it). This raises a permission error PermissionError: [Errno 13] Permission denied:
I want to trap this error, close the csv file (or close excel) without saving, and then try writing to the file again.
Is there a way to do this from within python?
try to catch any IOError for write access, kill excel with windows taskkill command if exception found
import os
import time
try:
with open(r'C:\file.csv', 'a') as f:
pass
except IOError:
os.system('taskkill /F /IM excel.exe')
time.sleep(2)
# do your csv read write, for example
with open(r'C:\file.csv', 'w') as f:
f.write('data')
Probably you need to search if swap file(current opened file) exist in the same directory or not .
If swap file exist then might need to delete that. before writing to that file
Read about it here
FYI: Delete Swap Files (Not programmatically though)
Correct me if I am wrong!

Python: Detect directory that cannot be detected in Windows 7

I am trying to write a detector that checks if a certain directory can be deleted using shutil.rmtree. I have a partial code finished as below that now works partial.
This code is now able to gives warning when any .exe files under the target folder is still running. But, this code is not yet able to flag warnings if any particular file under a folder is opened by an editor (which is another cause that makes a directory not deletable). Any guidance will be appreciated. Thanks in advance
Note: I've used open method to check for any locked file.
def list_locked_files(dir):
isLocked = False
for name in os.listdir(dir):
uni_name = unicode(name)
fullname = dir + u'/' + uni_name
if os.path.isdir(fullname):
list_locked_files(fullname)
else:
try:
f = open(fullname, 'r+')
f.close()
except IOError:
print fullname + u' is locked!'
isLocked = True
if isLocked is True:
print u'Please close the files/dir above !'
sys.exit(0)
It is not necessarily possible to determine whether a file deletion will succeed or fail on Windows. The file could be opened in a fully permissive share mode which means another attempt to open the file will succeed (no matter what kind of access you request).
The only way to tell whether a file can be deleted is to actually try it.
Even if there were an accurate way to tell beforehand, once you get the information it is instantly out of date. For example, after you call list_locked_files, a program could open another file in that directory which would cause rmtree() to fail.

Categories