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.
Related
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.
I have a situation where I have a file open using 'with'. I make some edits to the file and save it if the changes are successful. However whenever an error occurs during file handling, I want the file to be close without any changes done to the file. The with seem to overwrite the file and make the file empty.
Here is the code:
with open(path + "\\Config\\"+ filename, 'wb') as configfile:
config.write(configfile)
I get the "a bytes-like object is required, not 'str'" error for the above code which is fine. But all the content from the file has been removed when the error occurs.
How can be explicitly say the code to not save the changes and revert to the content that was existing before the change was made?
I use active python 3.5
If you don't want to make any changes to the original file unless everything is successful, what you should do is write your output to a new file. Then when you're done, rename that file to the original file.
If an error happens, you can use try/except to catch the error and delete the temporary file before exiting.
Open in a different mode than w. Using 'w' will created if it does not exist, otherwise it truncates whatever is in the file already. Use 'a' instead, which does not truncate by default. However, note that the file cursor will be at the end of the file. You you actually want to overwrite if there is no error, you'll have to f.seek(0) then f.truncate() manually.
EDIT
Actually, it might be better to use r+, which will not truncate automatically either, and the stream is at the beginning of the file instead of the end (like it is with 'a'), so only a simple f.truncate() will be necessary. See your options here. Basically, you definitely don't want 'w' but either one of 'r+' or 'a' depending on precisely the behavior you want.
This simple code
# This code will BLANK the file 'myfile'!
with open('myfile', 'w') as file:
raise Exception()
rather than merely throwing an exception, deletes all data in "myfile", although no actual write operation is even attempted.
This is dangerous to say the least, and certainly not how other languages treat such situations.
How I can prevent this? Do I have to handle every possible exception in order to be certain that the target file will not be blanked by some unforeseen condition? Surely there must be a standard pattern to solve this problem. And, above all: What is happening here in the first place?
You are opening a file for writing. It is that simple action that blanks the file, regardless of what else you do with it. From the open() function documentation:
'w'
open for writing, truncating the file first
Emphasis mine. In essence, the file is empty because you didn't write anything to it, not because you opened it.
Postpone opening the file to a point where you actually have data to write if you don't want this to happen. Writing a list of strings to a file is not going to cause exceptions at the Python level.
Alternatively, write to a new file, and rename (move) it afterwards to replace the original. Renaming a file as left to the OS.
The statement open('myfile', 'w') will delete all the contents on execution i.e. truncate the file.
If you want to retain the lines you have to use open('myfile', 'a'). Here the a option is for append.
Opening a file for writing erases the contents. Best way to avoid lost of data, not only in case of exceptions, also computer shutdown, etc. is to create a new temporary file and rename the file to the original name, when everything is done.
yourfile = "myfile"
try:
with tempfile.NamedTemporaryFile(dir=os.path.dirname(yourfile) or '.', delete=False) as output:
do_something()
except Exception:
handle_exception()
else:
os.rename(output.name, yourfile)
So I'm having an issue with using the zipfile module in Python. Currently when I try to compress a KML file to create a new KMZ file I'm missing the last few lines. It doesn't seem to matter how long the KML is. I assume this is because zipfile isn't writing the last zipped block.
kmz = zipfile.ZipFile(kmzPath , 'w')
kmz.write(kmlPath, 'CORS.kml', zipfile.ZIP_DEFLATED)
And yes before you ask I have imported zlib to do the compression. I've tried to use zlib at the lower level too but have the same issue. I'm stuck.
Any ideas?
Make sure that you called
kmz.close()
after the .write(...) command, otherwise the full contents of the file won't be flushed to disk. To make sure this happens automatically, always use the with context manager, as the file will be closed when the loop is exited:
with zipfile.ZipFile(kmzPath, 'w') as kmz:
kmz.write(kmlPath, 'CORS.kml', zipfile.ZIP_DEFLATED)
This is just a guess, but according to the zipfile documentation:
You must call close() before exiting your program or essential records will not be written.
You don't indicate that you are in fact calling kmz.close() - could that be the problem?
is there a way to open files without using QFileDialog.getOpenFileName parameter? The thing is, I have a some buttons that upon clicking them, a notepad will pop up in which you can type anything into the notepad. Then, you can save whatever you wrote in that notepad as a text file. What I want to do is, if I click the button again, I will reopen the file that I had previously edited via the notepad and can continue typing where I left off. However, I don't want to use getOpenFileName. Would it be possible to open a file without using this functionality? Below is my attempt but my if statement keeps evaluating to be false. If anyone could help that would be great. Thanks!
#Testing if the file already exists
if(os.path.exists("~/Desktop/" +self.fileName + ".txt")):
f = open(self.fileName + ".txt", 'r')
filedata = f.read()
self.text.setText(filedata)
f.close()
#Opens a new notepad if there wasn't a previous fileconstructed
else:
self.textBox = textBoxWindow(self.fileName)
self.textBox.show()
If you are on Winsows (you said the word Notepad), you can use the subprocess module to open any file with whatever program currently associated with the file type as follows:
import subprocess
self.filename = r'C:\test.txt'
subprocess.call(['start', self.filename], shell=True)
But the shell=True argument is kinda dangerous, especially of the filename comes as an input.
you can use the webbrowser module too, though not supported use of it I guess:
import webbrowser
webbrowser.open(self.filename)