amateurcoder
amateurcoder

Reputation: 1

Try/Except not running properly when opening files

I am trying to open a file with this Try/Except block but it is going straight to Except and not opening the file.

I've tried opening multiple different files but they are going directly to not being able to open.

import string

fname = input('Enter a file name: ')

try:
    fhand = open(fname)
except:
    print('File cannot be opened:', fname)
    exit()

counts = dict()
L_N=0
for line in fhand:
    line= line.rstrip()
    line = line.translate(line.maketrans(' ', ' ',string.punctuation))
    line = line.lower()
    words = line.split()
    L_N+=1
    for word in words:
        if word not in counts:
            counts[word]= [L_N]
        else:
            if L_N not in counts[word]:
                counts[word].append(L_N)
for h in range(len(counts)):
    print(counts)
out_file = open('word_index.txt', 'w')
out_file.write('Text file being analyzed is: '+str(fname)+ '\n\n')
out.file_close()

I would like the output to read a specific file and count the created dictionary

Upvotes: 0

Views: 67

Answers (1)

tritium_3
tritium_3

Reputation: 678

  1. make sure you are inputting quotes for your filename ("myfile.txt") if using python 2.7. if python3, quotes are not required.
  2. make sure your input is using absolute path to the file, or make sure the file exists in the same place you are running the python program.

for example, if your program and current working directory is in ~/code/ and you enter: 'myfile.txt', 'myfile.txt' must exist in ~/code/

however, its best you provide the absolute path to your input file such as

/home/user/myfile.txt

then your script will work 100% of the time, no matter what directory you call your script from.

Upvotes: 1

Related Questions