How to check if writing to a file fails in Python - python

how can I print out a message if the action was successful?
For example:
I want to write a string to a file, and if everything was ok, it should print out an "ok" message. It is possible with an easy way?
Edit:
for root, dirs, files in os.walk('/Users'):
for f in files:
fullpath = os.path.join(root, f)
if os.path.splitext(fullpath)[1] == '.'+ext:
outfile = open('log.txt', 'w')
outfile.write(fullpath)
outfile.close()

In short: python will tell you if there's an error. Otherwise, it is safe to assume everything is working (provided your code is correct)
For example:
a = "some string"
print "Variable set! a = ", a
would verify that the line a = "some string" executed without error.
You could make this more explicit like so:
try:
a = "some string"
print "Success!"
except:
print "Error detected!"
But this is bad practice. It is unnecessarily verbose, and the exception will print a more useful error message anyway.

Related

detect mime/extension of a file

I'm trying to write a program that when a user picks a file it can tell them whether it is a jpg, wav or another type (any other type goes under html). I got stuck in trying to process whether it is any of those types.
def openSoundOrPicture():
file=pickAFile()
print file
print len(file)
start=file.rfind('.')
print start
if start !=-1:
This is what I have so far but it doesn't work. (By the way, I'm really new to Python or any coding for the matter fact)
def openSoundOrPicture():
file=pickAFile()
print file
ln=len(file)
print ln
start=file.rfind('.')
print start
if start !=-1:
if file[start:ln]==".jpg"
print "File type:jpg"
elif file[start:ln]==".wav"
print "File type:wav"
You are basically trying to categorize files by their extension. Realize that there are other ways to do this like magic numbers. However, for what you asked to do, check out this code snippet:
recognized_types = ["jpg", "wav"]
default_type = "html"
file = pick_a_file()
file_extension = os.path.splitext(file)
if file_extension in recognized_types:
print "File Type: " + file_extension
else:
print "File Type: " + default_type

Make python code continue after exception

I'm trying to read all files from a folder that matches a certain criteria. My program crashes once I have an exception raised. I am trying to continue even if there's an exception but it still stops executing.
This is what I get after a couple of seconds.
error <type 'exceptions.IOError'>
Here's my code
import os
path = 'Y:\\Files\\'
listing = os.listdir(path)
try:
for infile in listing:
if infile.startswith("ABC"):
fo = open(infile,"r")
for line in fo:
if line.startswith("REVIEW"):
print infile
fo.close()
except:
print "error "+str(IOError)
pass
Put your try/except structure more in-wards. Otherwise when you get an error, it will break all the loops.
Perhaps after the first for-loop, add the try/except. Then if an error is raised, it will continue with the next file.
for infile in listing:
try:
if infile.startswith("ABC"):
fo = open(infile,"r")
for line in fo:
if line.startswith("REVIEW"):
print infile
fo.close()
except:
pass
This is a perfect example of why you should use a with statement here to open files. When you open the file using open(), but an error is catched, the file will remain open forever. Now is better than never.
for infile in listing:
try:
if infile.startswith("ABC"):
with open(infile,"r") as fo
for line in fo:
if line.startswith("REVIEW"):
print infile
except:
pass
Now if an error is caught, the file will be closed, as that is what the with statement does.
Move the try/except inside the for loop.
Like in:
import os
path = 'C:\\'
listing = os.listdir(path)
for infile in listing:
try:
if infile.startswith("ABC"):
fo = open(infile,"r")
for line in fo:
if line.startswith("REVIEW"):
print infile
fo.close()
except:
print "error "+str(IOError)
You're code is doing exactly what you're telling it to do. When you get an exception, it jumps down to this section:
except:
print "error "+str(IOError)
pass
Since there's nothing after that, the program ends.
Also, that pass is superfluous.
As per strictest interpretation of the question "continue even if there's an exception". Python gives us a keyword "finally" which executes a block of code no matter what precedes it. The only issue with this method will run a block of code regardless of the type of error, which might not be desirable for all cases.
try:
unreal = 3/0 # raises divide by zero exception
print(unreal)
# handles zerodivision exception
except :
print("Can't divide by zero, 0 has no multiplicative inverse")
finally:
# this block is always executed
print("Brahmagupta claimed that “zero divided by a zero is zero.”)

writing output of python cgi.print_environ() and cgi.print_form() to file

I'm trying to capture the output of cgi.print_form() and cgi.print_environ() and write them to files for later perusal, but it doesn't seem to be behaving as I'd expect.
I would expect this to simply write the output of the module to the path specified, but what I get is the cgi.print_form() output displayed to the page, nothing from cgi.print_environ() , the formpath file is empty, and the envpath file doesn't get created.
When I wrap the module in str() I get None in both files.
This was supposed to be a quick test to see what I'm getting from a remotely hosted form, but it just isn't working.
It's python 2.7.2
formfile = open(formpath, 'w')
formfile.write(cgi.print_form(form))
formfile.close()
envfile = open(envpath, 'w')
envfile.write(cgi.print_environ())
envfile.close()
EDIT: Just decided to write my own loop, but am still looking for a way to capture the print_form and print_environ function output.
for item in form:
key = form.getfirst(item)
fileitem = form[item]
if fileitem.filename:
formfile.write("%s is file %s\n" % (item, fileitem.filename))
filepath = '../fmtmp/%s_%s_%s' % (tstamp, item, fileitem.filename)
open(filepath, 'w').write(fileitem.file.read())
else:
formfile.write("%s = %s\n" % (item, key))
formfile.close()
envfile = open(envpath, 'w')
for var in os.environ:
envfile.write("%s = %s\n" % (var, os.environ[var]))
envfile.close()
Which gives me the added benny of saving whatever is uploaded as a file.
Note that x = cgi.print_environ() still outputs stuff if run in the interactive prompt (x will be None). CGI is interacting witht the web server over standard in/out. print_environ() is simply printing to standard out. It's point is to make it easy to debug enviroment by printing it in your browser.
EDIT: Actually sending it to file is somewhat tricky. You could try:
f = open('file', 'w')
old = sys.stdout
sys.stdout = f
cgi.print_environ()
f.flush()
sys.stdout = old
f.close()

display an error message when file is empty - proper way?

hi im slowly trying to learn the correct way to write python code. suppose i have a text file which i want to check if empty, what i want to happen is that the program immediately terminates and the console window displays an error message if indeed empty. so far what ive done is written below. please teach me the proper method on how one ought to handle this case:
import os
def main():
f1name = 'f1.txt'
f1Cont = open(f1name,'r')
if not f1Cont:
print '%s is an empty file' %f1name
os.system ('pause')
#other code
if __name__ == '__main__':
main()
There is no need to open() the file, just use os.stat().
>>> #create an empty file
>>> f=open('testfile','w')
>>> f.close()
>>> #open the empty file in read mode to prove that it doesn't raise IOError
>>> f=open('testfile','r')
>>> f.close()
>>> #get the size of the file
>>> import os
>>> import stat
>>> os.stat('testfile')[stat.ST_SIZE]
0L
>>>
The pythonic way to do this is:
try:
f = open(f1name, 'r')
except IOError as e:
# you can print the error here, e.g.
print(str(e))
Maybe a duplicate of this.
From the original answer:
import os
if (os.stat(f1name).st_size == 0)
print 'File is empty!'
If file open succeeds the value of 'f1Cont` will be a file object and will not be False (even if the file is empty).One way you can check if the file is empty (after a successful open) is :
if f1Cont.readlines():
print 'File is not empty'
else:
print 'File is empty'
Assuming you are going to read the file if it has data in it, I'd recommend opening it in append-update mode and seeing if the file position is zero. If so, there's no data in the file. Otherwise, we can read it.
with open("filename", "a+") as f:
if f.tell():
f.seek(0)
for line in f: # read the file
print line.rstrip()
else:
print "no data in file"
one can create a custom exception and handle that using a try and except block as below
class ContentNotFoundError(Exception):
pass
with open('your_filename','r') as f:
try:
content=f.read()
if not content:
raise ContentNotFoundError()
except ContentNotFoundError:
print("the file you are trying to open has no contents in it")
else:
print("content found")
print(content)
This code will print the content of the file given if found otherwise will print the message
the file you are trying to open has no contents in it

python mp3 meta-tag

I try to write a script than scan recursive a given directory and if found mp3 get and just print meta tag for it. What ever I passed to getEyeD3Tag I got an exception. Here is my code that i have written so far
def getEyeD3Tags(path):
try:
trackInfo = eyeD3.Mp3AudioFile(path)
tag = trackInfo.getTag()
tag.link(path)
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()
#return (tag.getArtist(),tag.getTitle(),tag.getAlbum())
except eyeD3.InvalidAudioFormatException:
print "File %s is not a mp3 file " % path
mp3Num=0
temp=os.walk(valid-folder-name)
for root, dirs, files in temp:
for i in files:
if os.path.join(root,i):
temp=os.path.splitext(i)
temp[1].lower()
if temp[1]=='.mp3':
mp3Path=os.path.join(root,i)
print mp3Path
getEyeD3Tags(mp3Path)
mp3Num+=1
raw_input()
#print "**"
else:
print "Error invalid path"
print "\n\n"
#raw_input()
print mp3Num
raw_input()
And BTW is it a way to get genre of mp3 file using eyeD3?
Thx in advance
To check if the file being parsed is a valid mp3, call the eyeD3.isMp3File(filename) method.
The following is from a short script I made to auto-sort my music folder.
def parseIDETag(self, path):
if eyeD3.isMp3File(path):
That way, if the file isn't an mp3, it'll just skip over it.
Also, str(tag.getGenre()) returns the genre as a string using eyeD3.

Categories

Resources