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)