Does try close the file after if it is successful? - python

I am trying to implement a quick code that checks to see if an Excel file is open. When the file is open, the IOError works and tells me the file is open. I can close and reopen the file at this point. If I do not have the file open, and either by calling a subprocess.call() or simply clicking on it, I an error.
Why does the try corrupt it if there is no error raises?
I have tried to close the file after the try but this does not work either.
file_path = (r'C:\users\Desktop\Build-Temp.xlsx')
if os.path.exists(file_path) is True:
report_closed = True
try:
report_opcl = open(file_path, 'w+')
# report_opcl.close()
except IOError:
print("file open already")
report_closed = False
# if report_closed is True:
# with report_opcl:
# subprocess.call(file_path,shell=True)
Errors
Excel cannot open the file 'Build-Temp.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

Opening a file with 'w' will delete the file contents. The docs call this "truncating". You might avoid the corruption using 'a' instead (not tested).
Anyway this is not going to work. By the time you check that report_closed is true another process might have opened the file.
I think you are trying to solve an unsolvable problem. There is no way to make sure that a file (identified by its path) will be available to another process in the future.

Related

Python: Check if the file can be read before processing the file

I am using a watchdog module to move video files to a different folder. But the problem is the move process starts as soon as the file is created and is still under copy process from its origin location. To overcome this, I did a file size check, but windows is not refreshing the filesize in real time and hence the file size check is not proving to be useful.
Is there another way to check if the file is fully copied (maybe if file can be read/opened?) prior to moving the file. I tried the code below but to no avail.
while True:
try:
with open(os.path.basename(event.src_path)) as f:
s = f.read()
print ("can read the file now")
except IOError:
print ("cannot read the file")
#shutil.move operation here
Any ideas will be appreciated.

Unable to open a previously opened H5

I have a simple python script that opens an H5 file, edits some of the data and closes it. For some reason it works the first time I run the script but in crashes on the second try.
I was expecting that the error was that I do not close the file but actually I do. As you can see below I edit the fields called backR frontR and I create two new ones Manufacturer and Status then I close.
f = h5py.File(filename, 'r+')
backR = f['back_R']
backR[...] = SelectedBackCoat
frontR = f['front_R']
frontR[...] = SelectedFrontCoat
f.create_dataset('manufacturer', data=SelectedManu)
f.create_dataset('status', data=SelectedState)
f.close()
The second time I run the script for the same file to treat I get the following:
File "h5py\h5f.pyx", line 85, in h5py.h5f.open
OSError: Unable to open file (file is already open for read-only)
The file is still opened, maybe your script didn't reach f.close()? From this answer to this question, you can try to force close all opened files first. Although you should really debug why your file is still opened.
pytables (which h5py uses) keeps track of all open files and provides
an easy method to force-close all open hdf5 files.
import tables
tables.file._open_files.close_all()
If you use the with statement you can enforce closing of file, even if a exception occurs:
with h5py.File(filename, 'r+') as f:
f.write(...)

Why do I get Python IOError: [Errno 13] Permission denied on writing to a file?

I cannot figure out what I am doing wrong. I am running some tests and writing the results to a file. The portion of the code which writes to a file is the following (in a class called Tester):
#staticmethod
def printHeader(resultsFileName):
if not os.path.isfile(resultsFileName):
# The file does not exist, thus
# we need to print the header
# Opens the results file
with open(resultsFileName,"a") as file:
# Prints the header
file.write("A long header")
#staticmethod
def printResults(resultsFileName,otherArguments):
# Prints the header if it does not exist
Tester.printHeader(resultsFileName)
# Prints the results
with open(resultsFileName,"a") as file:
file.write(otherArguments)
Sometimes I get this error:
Traceback (most recent call last):
File "main.py", line 74, in <module>
File "tester.py", line 88, in methodOne
File "tester.py", line 441, in printResults
File "tester.py", line 428, in printHeader
IOError: [Errno 13] Permission denied: 'results.txt'
while other times it runs smoothly. I cannot figure out where the problem is. Any ideas?
NOTE1: I have rwxpermission on the directory where the file is written.
NOTE2: The error happens after several lines of results have already been written. Thus, it happens when the code is checking whether the header should be printed or not (but it is not supposed to print it, since the file exists).
UPDATE 1:
As suggested, I have changed my code to avoid opening and closing the file multiple times. Now it writes everything in one shot. This is the updated code:
#staticmethod
def printResults(resultsFileName,otherArguments):
# Prints the header if it does not exist
if not os.path.exists(resultsFileName):
# The file does not exist, thus
# we need to print the header
# Opens the results file
# HERE IS WHERE ERRNO 13 HAPPENS
# STRANGELY, THE FILE DOES EXIST
# AS SEVERAL LINES OF RESULTS
# HAVE ALREADY BEEN WRITTEN
with open(resultsFileName,"w") as file:
# Prints the header
file.write("A suitable header")
# Prints the results
file.write(otherArguments)
else:
# Prints the results
with open(resultsFileName,"a") as file:
file.write(otherArguments)
It seems that os.path.exists() at some point returns FALSEeven if the file does exist. Probably, there is something revoking me permission to write (perhaps the file is not properly closed after writing?).
The explanation of os.path.exists() says that:
On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.
UPDATE 2
I have changed my code to the following, to avoid os.path.isfile():
# Opens the results file
with open(resultsFileName,"a") as file:
if file.tell() == 0:
# Prints the header
file.write("Header")
# Prints the results
file.write(otherArguments)
file.close()
else:
# Prints the results
file.write(otherArguments)
file.close()
Nevertheless, ERRNO 13 happens at with open(resultsFileName,"a") as file:.
I have rwpermissions both on the folder and on the file, on which several lines are written before the error happens. The OS is Linux.
Try closing the file result.txt before running the program (I'd its open).
Check the writing permissions.
Another cause might be writing into a .txt file in a directory without those permissions. Try running python from the specified directory.
os.path.isfile(path) returns True if path exists AND is a file AND you have (at least) read permissions on it. IOW, it returns False if path exists but is a directory and/or you don't have permissions on it. So your test is wrong from the start - os.path.exists() would be a better choice. But anyway: those operations are not atomic so the file could well be created between the moment where you test for it's existence and the moment where you try to open it, so the whole design is actually unsafe. Also, stating, opening and closing a file are all costly operations, so I suggest - if possible - that you rethink your whole design to open a file only once and only close it once when you're done.
You can check if the file is open with another program. If so, you can try closing them all.
Cheers!
Surely it will work

os.close to close open word document

I am trying to check if a file exists, if it does exist, I want to check if it is open by trying to rename it. The except block is trying to close the open file using os.close. When I try to close the file I get "TypeError: an integer is required".
import os
filepath = "C:\Users\oneilp6\Desktop"
file1 = filepath + "\\HelpFile.docx"
file2 = filepath + "\\HelpFile2.docx"
if os.path.exists(file1):
try:
os.rename(file1,file2)
except:
os.close(file1)
Anyone have any thoughts or ideas? I am trying to close a word document that is actually open in MS Word. Is there a way to do that?
You are checking whether the file is open by a different application on your computer. If it is, there isn't much this program can do about it. You don't get to close other program's files. You could potentially hunt down that program and kill it, but even that isn't easy. There are some suggestions at https://serverfault.com/questions/1966/how-do-you-find-what-process-is-holding-a-file-open-in-windows.
There is no file opened in the except. so no need to call os.close().
https://docs.python.org/2/library/os.html#os.rename
os.close() This function is intended for low-level I/O and must be
applied to a file descriptor as returned by os.open() or pipe(). To
close a “file object” returned by the built-in function open() or by
popen() or fdopen(), use its close() method.

Writing to a file errors and permission errors

while True:
try:
enterName = input("Enter the name of the file:") + ".txt"
latinFile = open(enterName,"r")
read = latinFile.readlines()
for lines in read:
store.append(lines.strip())
checkSquare (store)
print ("File:")
for content in store:
print (content)
saveData(store)
I think the problem is with the code for saving the file contents.
The aim is for the code to open the file,read the contents and it checks to see if the format of the file is correct etc and then if that is all true and it works, it will save the file again (saveData) but it will rename the file so that it says in the directory that it has been validated.
However, the code isn't working ( the os.rename part) and also I keep getting a permissionerror and I don't know how to fix it.
Error message:
Traceback (most recent call last):
File "C:\Users\---\Desktop\python\idkll.py", line 44,in <module>
saveData(store)
File "C:\Users\---\Desktop\python\idkll.py", line 18, in saveData
os.rename (fileName,"VALIDATED" + fileName)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'OPENEDve.txt'
You should close your files as soon as you finish reading from them or writing to them. And you should close the file before attempting to rename it. You can either use the file's .close() method, or use a with statement so that files get closed automatically.
Incidentally, your saveData() function should probably not prompt the user for the filename: just pass it the name you already have in enterName. Also, prepending "VALIDATED" to the filename is not a good strategy. It's ok if you're just using relative filenames in the current directory, but it will make a mess of a proper file path.
In response to the update:
saveFile does not contain a file name string, it's a Python object representing your open file (also known as a file handle). The name of that file is the string in enterName. So you need to do something like
os.rename(enterName, enterName + "VALIDATED")
Just swap os.rename (fileName,"VALIDATED" + fileName) and file.close() lines inside saveData() function.
You should close the file prior to trying to rename it. The error is because your program is actually using the file it is trying to rename.

Categories