0

I have to raise ValueError('Invalid file name') if my infile or outfile or the two of them is empty

this is the code in python:

def get_x_freqs(infile, outfile, x):
    # Write the rest of the code for question 3 below here.
    f =None
    try:
        f=open(infile, "r")
        if infile=='':
            raise ValueError('Invalid file name')

        else:
            d={}
            for line in f:
                element = line.split()
                for word in element:
                    d[word]=d.get(word,0)+1

        try:
            f=open(outfile, "w")
            if outfile=='':
                raise ValueError('Invalid file name')
            else:
                sorted_elements = sorted(d.keys(), key=d.get, reverse=True)
                for e in sorted_elements[:x]:
                    print(e, ':', d[e])

        finally:
            if f!= None:
                f.close()


in_filename = 'C:\\Users\\shirl\\Desktop\\מדעים להייטק\\פיתון\\Exercises\\ex.5\\q3.txt'
out_filename = 'C:\\Users\\shirl\\Desktop\\מדעים להייטק\\פיתון\\Exercises\\ex.5\\q3_out.txt'

get_x_freqs(in_filename, out_filename, 3)
luigigi
  • 4,146
  • 1
  • 13
  • 30
shirleyb
  • 1
  • 1
  • did you look at this : https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python – Ali Yaman Dec 09 '19 at 12:43
  • What do you mean by "if outfile is empty"? The file is always empty when you open it in write mode. Do you mean if there is no data to write? – Thierry Lathuille Dec 09 '19 at 12:51

1 Answers1

0

Your try-except blocks should more look like this:

try:
    f=open(infile, "r")
    d = {}
    for line in f:
        element = line.split()
        for word in element:
            d[word] = d.get(word, 0) + 1
except:
    raise ValueError('Invalid file name')
luigigi
  • 4,146
  • 1
  • 13
  • 30