Masoumeh Javanbakht
Masoumeh Javanbakht

Reputation: 135

Trouble with opening a file in python

I wrote the following program. The program is supposed to get the name of a file having some chemical data and an input from the user to determine if the element is already one of the elements of the file or not. But unfortunately, in the first step, I receive this message that enter a valid name for the file. I don't know where the problem is?! Any help is really appreciated.

# Determine the name of a chemical element
import re

# Read the name of a file from the user
filename = input("Enter a filename:")

try:

    # Open the file
    f1 = open(filename, "r")

    # Read an element from the user
    elem = input(
        "Enter the name of the element or the number of protons (" * " to exit): "
    )

    while elem != "*":

        try:

            int_elem = int(elem)

            # Search in each line for the entered input
            for line in f1:

                if re.findall(elem, line) != []:

                    # Split the line to its elements
                    elem_line = line.split(" ")

                    # Print the name of element
                    print("The name of element is {}".format(elem_line[0]))

                    # print the symbol of the elemnt
                    print("The symbol of element is {}".format(elem_line[1]))

                    # Print the number of elements
                    print(
                        "The number of protons in {} is {}".format(
                            elem_line[0], elem_line[2]
                        )
                    )

                else:

                    # Display if there is no elemt with this number of protons
                    print("There is no element with this number of protons")
                    break

        except:

            # Serach for th element in each line of the file
            for line in f1:

                if re.findall(elem, line) != []:

                    # Split the line to its elements
                    elem_line = line.split(" ")

                    # Print the number of elements
                    print(
                        "The number of protons in {} is {}".format(
                            elem_line[0], elem_line[2]
                        )
                    )

        elem = input("Enter the name of the lement(" * " to exit):")
except:

    print(" Enter a valid name for the file ")

If I run the program, I will get the following output:

Enter a filename:'chemic.txt'
Enter a valid name for the file

Upvotes: 0

Views: 93

Answers (2)

AKX
AKX

Reputation: 169338

It'll be hard to know what the problem is since any and all exceptions that occur within your code are "swallowed" by that top-level except: block.

Wrapping all of your program in an exception handler is not good form – instead handle the errors (or don't! – your user will get e.g. a FileNotFoundError, which is probably more than suitable) as they occur.

Something like this might work for you.

import re

filename = input("Enter a filename:")
f1 = open(filename, "r")

while True:
    f1.seek(0)  # We need to be at the start of the file for every user input.

    # Read an element from the user
    elem = input("Enter the name of the element or the number of protons (* to exit): ")
    if elem == "*":
        break  # exit the loop

    # Search in each line for the entered input
    for line in f1:
        if re.search(elem, line):
            # Split the line to its elements
            elem_line = line.split(" ")
            print("The name of element is {}".format(elem_line[0]))
            print("The symbol of element is {}".format(elem_line[1]))
            print("The number of protons in {} is {}".format(elem_line[0], elem_line[2]))
            break  # found a match, exit the loop
    else:
        print("There is no element with this name or number of protons")

Upvotes: 2

Holloway
Holloway

Reputation: 7377

The line

elem = input(
    "Enter the name of the element or the number of protons (" * " to exit): "
)

Is not valid python. You are trying to multiply a string by another string. I suspect you want to either escape the " (with \") around the * or use ' instead.

The TypeError that is raised is caught by your catch-everything block and the message is assuming the error is from elsewhere. As others have said, you ideally only want to wrap the bit that you expect to raise the exception and then only catch the specific type that you are expecting.

Upvotes: 1

Related Questions