Python - test if a file has already been open - python

I would testing if a file has already been open before writing.
Here my code :
with open(file_five, 'w') as f:
f.write(xml)
I would something as this code example :
if "file_five has already been open"
with open(file_five, 'w') as f:
f.write(xml)
else:
...

There are two ways:
1-> For Excel specific
try:
myfile = open("file_five.csv", "r+") # or "a+", whatever you need
except IOError:
print "Could not open file! !"
with myfile:
do_stuff()
2 -> For any file (Rename approach)
import os
try:
os.rename('file.xls', 'tempfile.xls')
os.rename('tempfile.xls', 'file.xls')
except OSError:
print('File is still open.')

Related

Why can't handle "io.UnsupportedOperation" error by try-except

Running the following code will raise an io.UnsupportedOperation error, because the file is open in "write" mode -
with open("hi.txt", "w") as f:
print(f.read())
The output is -
io.UnsupportedOperation: not readable
So, we can try to cover this up by doing this -
try:
with open("hi.txt", "w") as f:
print(f.read())
except io.UnsupportedOperation:
print("Please give the file read permission")
Output -
NameError: name 'io' is not defined
Even removing "io." spits out the same error -
try:
with open("hi.txt", "w") as f:
print(f.read())
except UnsupportedOperation:
print("Please give the file read permission")
Output -
NameError: name 'UnsupportedOperation' is not defined
Why isn't it working? Isn't "io.UnsupportedOperation" an error?
The io.UnsupportedError is found in the module io. Therefore, before we can use it, we need to import io
import io
then when we are testing for the error in the try except clause we can use io.UnsupportedError.
This gives us:
import io
try:
with open("hi.txt", "w") as f:
print(f.read())
except io.UnsupportedOperation as e:
print(e)
or if you are only using the io module for checking this specific error.
from io import UnsupportedError
try:
with open("hi.txt", "w") as f:
print(f.read())
except UnsupportedOperation as e:
print(e)

Gunzip all the files present in source directory in Python

I have written a code to gunzip all the files present in the source folder. But I want to include the check that if gunzipped file doesn't exist then gunzip it else move to next file.
source_dir = "/Users/path"
dest_dir = "/Users/path/Documents/path"
for src_name in glob.glob(os.path.join(source_dir, '*.gz')):
base = os.path.basename(src_name)
dest_name = os.path.join(dest_dir, base[:-3])
with: gzip.open(src_name, 'rb') as infile, open(dest_name, 'wb') as outfile:
try:
for line in infile:
print ("outfile: %s" %outfile)
if not os.path.exists(dest_name):
outfile.write(line)
print( "converted: %s" %dest_name)
except EOFError:
print("End of file error occurred.")
except Exception:
print("Some error occurred.")
I have used os.path.exist to check whether the file exists or not, but it seems like os.path.exist doesn't work here.
I think you have misplaced the path.exists call. It should be:
source_dir = "/Users/path"
dest_dir = "/Users/path/Documents/path"
for src_name in glob.glob(os.path.join(source_dir, '*.gz')):
base = os.path.basename(src_name)
dest_name = os.path.join(dest_dir, base[:-3])
if not os.path.exists(dest_name):
with gzip.open(src_name, 'rb') as infile, open(dest_name, 'wb') as outfile:
try:
for line in infile:
print("outfile: %s" % outfile)
outfile.write(line)
print("converted: %s" % dest_name)
except EOFError:
print("End of file error occurred.")
except Exception:
print("Some error occurred.")
Also as #MadPhysicist emphasized:
"doing the check after open(..., 'wb') (as you did in your original code), will always say that the file exists because that is what open(..., 'w') does"
On top of that even if you made some other check for the necessity of gunzipping, doing it where you've put it will do the check on every line, which is completely redundant as the result will be the same for all lines (exists/not-exists).

Why doesn't "try, except" work with classic "open(fname, 'r')" in python?

I have a function that opens a file and returns an opened file object.
def read_any():
try:
opened = gzip.open(fname, 'r')
except IOError:
opened = open(fname, 'r')
return opened
When I attempt to run this function on some non-zipped file except condition does not get triggered and the function crashes with the message: IOError: Not a gzipped file.
Ok, now I try and do the same with with statement:
def read_any2():
try:
with gzip.open(fname, 'r') as f:
return f.read()
except IOError:
with open(fname, 'r') as f:
return f.read()
Now, if I try to run the same file the function works as intended.
Can you explain why doesn't except condition get triggered?
To see what's going on, test it in a REPL:
>>> import gzip
>>> f = gzip.open('some_nongzipped_file', 'r')
You will see that this doesn't raise an error. Once you, however, read from the object:
>>> f.read()
... (snip)
OSError: Not a gzipped file
, it raises the error.
In short: Simply creating the file object doesn't read anything from the file yet, and thus doesn't know if it should fail or not.
Since in the first example you just return the file object, when you try to read from it later it will raise the exception there (outside your raise-except block). In your second example you return f.read() which reads and therefore raises the exception. It has nothing to do with the with block, as you can see if you remove it:
def read_any_mod():
try:
opened = gzip.open(fname, 'r')
return opened.read()
except IOError:
opened = open(fname, 'r')
return opened.read()

Python: Checking for JSON files and creating one if needed

I'm currently making a program that requires a JSON database file. I want the program to check for the file, if it's there then it's perfect, run the rest of the program, but if it doesn't exist create 'Accounts.json' with {} inside the file, instead then run the program.
How would I do this? Whats the most efficient way.
Note: I use this for checking, but how would I create the file:
def startupCheck():
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
# checks if file exists
print ("File exists and is readable")
else:
print ("Either file is missing or is not readable")
I believe you could simply do:
import io
import json
import os
def startupCheck():
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
# checks if file exists
print ("File exists and is readable")
else:
print ("Either file is missing or is not readable, creating file...")
with io.open(os.path.join(PATH, 'Accounts.json'), 'w') as db_file:
db_file.write(json.dumps({}))
This is how i did it. I hope it helps.
edit, yeey it looks like a code now :D
import json
import os
def where_json(file_name):
return os.path.exists(file_name)
if where_json('data.json'):
pass
else:
data = {
'user': input('User input: '),
'pass': input('Pass input: ')
}
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
How about wrapping the open file in a try/except? I'm not a professional Python coder, so feel free to weigh in if this is not a kosher approach.
try:
with open('Accounts.json', 'r') as fp:
accounts = json.load(fp)
except IOError:
print('File not found, will create a new one.')
accounts = {}
# do stuff with your data...
with open('Accounts.json', 'w') as fp:
json.dump(accounts, fp, indent=4)
w+ opens with write permissions.
The + creates a new file if one is not found.
filename = 'jsonDB.json'
def openFile():
with open(filename, 'w+') as f:
f.write('{}')
f.close
openFile()

Python: Readline returns error after 10 lines

I'm trying to use readline on file in a for loop. The problem is that I start getting I/O errors. It seems that I get I/O error after 10 readlines.
Here is my function:
def getAll():
with open("nodes2.txt", "r+") as f:
for i in range(0, 200):
print "**%s**"%(i)
try:
file = f.readline()
file = file[:-1]
# print "*%s*" % (file)
entities = getAllPagesEntities(file)
# print entities
for en in entities:
try:
dict = getFirmAttributes(en)
printToFile(dict)
except Exception,e:
with open("log_getFirmAttributes.txt","a") as f:
f.write(str(e))
f.write("\n")
except Exception,e:
with open("log_readFile.txt","a") as f:
f.write(str(e))
f.write("\n")
Here is a printed catched exception:
I/O operation on closed file
I think that this problem can't be caused by another used functions so I don't attach them here. I thought that it is caused by the file used but when I try to readline 200 and print them, everything works perfect.
with open("nodes2.txt", "r+") as f:
for i in range(0, 200):
print f.readline()
Have you any idea what could be the problem? Thanks
Following lines in the except block overwrites f causing open file to be closed.
with open("log_readFile.txt","a") as f:
f.write(str(e))
f.write("\n")
Change the name f for the file for appending to another name will solve the problem:
with open("log_readFile.txt", "a") as logf:
logf.write(str(e))
logf.write("\n")

Categories

Resources