Проблема с открытием файла в Python - PullRequest
0 голосов
/ 05 марта 2019

Я написал следующую программу. Предполагается, что программа получит имя файла, содержащего некоторые химические данные, и данные от пользователя, чтобы определить, является ли элемент уже одним из элементов файла или нет. Но, к сожалению, на первом этапе я получаю это сообщение, в котором вводится правильное имя файла. Я не знаю, где проблема ?! Любая помощь очень ценится.

# 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 ")

Если я запустите программу, я получу следующий вывод:

Введите имя файла: 'chemic.txt'
Введите действительное имя для файла

Ответы [ 2 ]

2 голосов
/ 05 марта 2019

Будет трудно понять, в чем проблема, поскольку все исключения, возникающие в вашем коде, "проглатываются" этим блоком except: верхнего уровня.

Оборачивает всю вашу программу вобработчик исключений не является хорошей формой - вместо этого обрабатывайте ошибки (или не делайте!) ваш пользователь получит, например, FileNotFoundError, что, вероятно, более чем подходит) по мере их возникновения.

Что-то подобное можетработа для вас.

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")
1 голос
/ 05 марта 2019

Линия

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

Не является допустимым питоном. Вы пытаетесь умножить строку на другую строку. Я подозреваю, что вы хотите либо избежать "\") вокруг *, либо использовать ' вместо.

Поднятый TypeError перехватывается вашим блоком catch-everything, и сообщение предполагает, что ошибка произошла из другого места. Как уже говорили другие, в идеале вам нужно только обернуть бит, который вы ожидаете, чтобы вызвать исключение, а затем перехватить только тот ожидаемый тип.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...