Opening File in 2 conditions - python

I am working on a .txt file. But there are 2 conditions. I do not know which one will occur. It depends on the user's decision.
My program will write what the user will make, but if there is no such a file in my program will have to create a file which its name what the user enter on the command line. Nevertheless, if there is a file my program will make all operation over this file.
So, I have tried a+ command like file = open(sys.argv[1],"a+") but this did not work well. It has created a new file it didn't exist. But it did not read my file which already exists. Do you think how can I open the file that works with two conditions?

You want to use a try statement. Something like:
try:
# Try to open the file
file = open(sys.argv[1], "r")
except FileNotFoundError:
# If the file does not exist, create it
file = open(sys.argv[1],"a+")

Related

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(...)

Does try close the file after if it is successful?

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.

Python writing data to file only works when run from console

If I run
file = open("BAL.txt","w")
I = '200'
file.write(I)
file.close
from a script, it outputs nothing in the file. (It literally overwrites the file with nothing)
Furthermore, running cat BAL.txt just goes to the next line like nothing is in the file.
But if I run it line by line in a python console it works perfectly fine.
Why does this happen. ( I am a begginner learning python the mistake may be super obvious. I have thrown about 2 hours into trying to figure this out)
Thanks in advance
You aren't closing your file properly. To close it you are missing the () at the end of file.close so it should look like this:
file = open("BAL.txt", "w")
file.write("This has been written to a file")
file.close()
This site has the same example and may be of some use to you.
Another way, especially useful when you are appending multiple values into a single file is to use something like with open("BAL.txt","w") as file:. Here is your script rewritten to include this example:
I = '200'
with open("BAL.txt","w") as file:
file.write(I)
This opens our file with the value file and allows us to write values to it. Also note that file.close() is not needed here and when appending text w+ needs to be used.
to write to a file you do this:
file = open("file.txt","w")
file.write("something")
file.close()
when you use file.write() it deletes all of the contents of the file, if you want to write to the end of the file do this:
file = open("file.text","w+")
file.write(file.read()+"something")
file.close()
There are other ways to do this but this one is the most intuitive (not the most efficient), also the other way tends to be buggy so there is no reason to post it because this is reliable.
Firstly, you're missing the parentheses when you're closing the file. Secondly, writing to a file should be done like this:
file = open("BAL.txt", "w")
file.write("This has been written to a file")
file.close()
Let me know if you have any questions.

Python IOError, cannot find file in directory

I'm supposed to upload a database for an assignment, but I'm having a problem. These are the instructions:
This application will read the mailbox data (mbox.txt) count up the
number email messages per organization (i.e. domain name of the email
address) using a database with the following schema to maintain the
counts.
CREATE TABLE Counts (org TEXT, count INTEGER) When you have run the
program on mbox.txt upload the resulting database file above for
grading. If you run the program multiple times in testing or with
different files, make sure to empty out the data before each run.
The data file for this application is the same as in previous
assignments: http://www.pythonlearn.com/code/mbox.txt.
Because the sample code is using an UPDATE statement and committing
the results to the database as each record is read in the loop, it
might take as long as a few minutes to process all the data. The
commit insists on completely writing all the data to disk every time
it is called.
The error message that it keeps sending me is:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
fh = open(fname)
IOError: [Errno 2] No such file or directory: 'mbox.txt'
I saved them both in the same folder.
Can anybody help with this?
The code that I entered is here
Your code is having problem to find the file mbox.txt. It has nothing to do
with anything in the database as you did not run so far yet.
Good practice (at least during development) is to make sure, the things you
hope are true are really true. For this purpose I would use following code
which makes sure, the file really exists.
import os.path
fname = "mbox.txt"
assert os.path.exists(fname), "The file shall exist"
If you happen to run the code in situation, the file does not exist, it will throw an
AssertionError telling you what went wrong.
This exception is very practical as it will tell you quickly what assumption does not holds true and
you know, what to fix.
Your code is looking for a file called mbox.txt and not finding it. My guess is that open(fname) is looking for mbox.txt in the current directory, but the code is being run from a different directory.
Something like this might help resolve your issue:
import os
# figure out directory of the Python file
mdir = os.path.dirname(os.path.abspath(__file__))
# assuming that mbox.txt is in the same folder as the Python file,
# get the path to that file
mpath = os.path.join(mdir, 'mbox.txt')
# open the file
with open(mpath, 'r') as fh:
# ...
Another approach is using command line arguments. Perhaps there are other files like mbox.txt that you want to work with. In these cases, you could accept the path to mbox.txt as a command line option:
import argparse
argp = argparse.ArgumentParser(description='foo the mbox')
argp.add_argument('mbox_path', help='Path to mbox file')
opts = argp.parse_args()
with open(opts.mbox_path, 'r') as fh:
# ...
Or get fancier and use argparse.FileType for the type argument to argparse.add_argument.

python 2.7: Testing text file in idle

I m using the command testFile = open("test.txt") to open a simple text file and received the following: Does such errors occur due to the version of python one uses?
IOError: [Errno 2] No such file or directory: 'Test.txt
add an "a+" mode argument on to your open, this will create the file if it doesn't exist:
testFile = open("test.txt", "a+")
Syntax for opening file is:
file object = open(file_name [, access_mode][, buffering])
As you have not mentioned access_mode(optional), default is 'Read'. But if file 'test.txt' does not exists in the folder where you are executing script, it will through an error as you got.
To correct it, either add access_mode as "a+" or give full file path e.g. C:\test.txt (assuming windows system)
The error is independent from the version, but it is not clear
what you want to do with your file.
If you want to read from it and you get such an error, it means that your file is not where you think it is. In any case you should write a line like testFile = open("test.txt","r").
If you want to create a new file and write in it, you will have a line like
testFile = open("test.txt","w"). Finally, if your file already exists and you want to add things on it, use testFile = open("test.txt","a") (after having moved the file at the correct place). If your file is not in the directory of the script, you will use commands to find your file and open it.

Categories