-3

if the input file has any non digit values, unable to print ValueError for ex: if the input file has values:

100
200
300

The values should be appended to the list

if values are:

100
s
200

it should pop out error

provided in code

m = 0
j = []

with open("file_name.txt", mode="r") as f:
    file_lines = f.readlines()
    while m < len(file_lines):
        values = file_lines[m].strip()
        try:
            if values.isdigit():
                j.append(values)
        except ValueError:
            print("Input values given in file_name.txt are not integers '%s'" % values.strip())
            pass
        m = m + 1

f.close()
print(j)

output should be print("Input values given in file_name.txt are not integers '%s'" % values.strip()) if input values have any non digit value

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
suraj
  • 35
  • 1
  • 7
  • Read about exceptions. `if values.isdigit():` does not raise any `ValueError` - Exception. `number = int(values):` would. – Patrick Artner Aug 28 '19 at 07:04
  • Read answers to [asking-the-user-for-input-until-they-give-a-valid-response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) to adapt your code. – Patrick Artner Aug 28 '19 at 07:05

1 Answers1

0
m = 0
j = []

with open("file_name.txt", mode="r") as f:
    file_lines = f.readlines()
    while m < len(file_lines):
        values = file_lines[m].strip()
        try:
            if values.isdigit():
                j.append(values)
            else:
                raise ValueError("Input values given in file_name.txt are not integers '%s'" % values.strip())
        except ValueError:
            print("Input values given in file_name.txt are not integers '%s'" % values.strip())
            pass
        m = m + 1

f.close()
print(j)