-2

I am trying to get this to run on each line of a .txt file.

D1 =int(lines[0])*10
D2 =int(lines[1])*9
D3 =int(lines[2])*8
D4 =int(lines[3])*7
D5 =int(lines[4])*6
D6 =int(lines[5])*5
D7 =int(lines[6])*4
D8 =int(lines[7])*3
D9 =int(lines[8])*2
D10=int(line[9])*1
Sum =(D1+D2+D3+D4+D5+D6+D7+D8+D9)
Mod = Sum % 11

D11= 11 - Mod
if D11 == 10:
    D11 = 'X'

Basically, the text file contains ISBN-10 numbers that I need to verify by running this code on each of the numbers inside of the text file. Here is where lines is defined because the text file contains "-" and I need to remove those before i start the process shown above.

filename = input("Enter the name of the .txt file: ")
file = open(filename, "r")
lines = file.read()
if "-" in lines:
    lines = lines.replace("-", "")
lines = file.readline()
while lines:
    D1 =int(lines[0])*10
    D2 =int(lines[1])*9
    D3 =int(lines[2])*8
    D4 =int(lines[3])*7
    D5 =int(lines[4])*6
    D6 =int(lines[5])*5
    D7 =int(lines[6])*4
    D8 =int(lines[7])*3
    D9 =int(lines[8])*2
    D10=int(lines[9])*1
    Sum =(D1+D2+D3+D4+D5+D6+D7+D8+D9)
    Mod = Sum % 11

    D11= 11 - Mod
    if D11 == 10:
        D11 = 'X'
    if D10 == D11:
        print("Your ISBN-10's are Valid!")
    else:
        print("Your ISBN-10's are invalid")

4 Answers4

1

You can use a for loop:

for i,line in enumerate(textFile):
    #code to run on each line  

Where line is the value of the current line in the loop and i is the line number so let's say your text file was:

John
Doe

Then the for loop would be:

i as 0
line as John

on the first run and so on.

  • enumerate makes a tuple so the whole piece of code `enumerate(list_item)` would equal (position, value) –  Nov 27 '17 at 12:59
1

You do not have to use while to iterate on each line of file and each digit in line.
You have to use for loop with enumerate() builtin function like this:

filename = input("Enter the name of the .txt file: ")
file = open(filename)
lines = file.readlines()

# # for testing
# lines = [
# '1-2345678-90\n',  # invalid
# '18-619727-17\n'  # valid
# ]

# iterate on lines
for line in lines:
    SUM = 0

    # remove '\n', new line, from line
    line = line.strip()

    # remove '-' from line
    line = ''.join(digit for digit in line if digit != '-')

    # iterate on line's digits
    for i, digit in enumerate(line):
        SUM += int(digit) * (len(line) - i)

    Mod = SUM % 11

    # print line for demonstration
    print('ISBN-10: ', line)

    # zero remainder = valid ISBN
    if Mod == 0:  # if not Mod:
        print("Your ISBN-10's are Valid!")
    else:
        print("Your ISBN-10's are invalid")

will print:

ISBN-10:  1234567890
Your ISBN-10's are invalid
ISBN-10:  1861972717
Your ISBN-10's are Valid!
Elis Byberi
  • 1,422
  • 1
  • 11
  • 20
1

You can do the processing on-the-fly as you're reading in the file. For testing I used a file named isbn10.txt that contained these made-up numbers (after the first, which is valid, every other following number is invalid).

0-201-53082-1
0-20A-53082-1
0-306-40615-2
0-307-40615-9
0-507-40615-X

Here's the code to do it. ISBNs digits are base 11 and can be 0-9 or X, not just 0-9 as with base 10, so that has to be taken care of when doing computations. Also note that the following doesn't save the numbers anywhere, so that would need to be added it you want to keep them around for some reason. It also does different calculations than your code for validating them which is based on information in Wikipedia article on the subject (see the section titled ISBN-10 check digits). There's also a description of how it's used in the ISBN 10 section of Wikipedia article on Check digits.

# Dictionary to map ['0'-'9', 'X', 'x'] to [0-9, 10, 10].
BASE10 = {digit: i for i, digit in enumerate('0123456789X')}
BASE10['x'] = BASE10['X']  # Allow upper and lowercase 'x's.

#filename = input("Enter the name of the .txt file: ")
filename = 'isbn10.txt'  # Hardcoded for testing.

invalid_numbers_count = 0
with open(filename, "r") as file:
    for numbers_count, line in enumerate(file, 1):
        # Remove any leading or trailing whitespace and dashes from number.
        digits = line.rstrip().replace('-', '')

        try:
            chksum = sum((i * BASE10[digit]) for i, digit in enumerate(digits, 1))
        except KeyError:  # Invalid digit.
            chksum = 1  # Any non-multiple of 11.

        if chksum % 11 == 0:
            print('ISBN {} is valid'.format(line.strip()))
        else:
            print('ISBN {} is invalid'.format(line.strip()))
            invalid_numbers_count += 1

print("{} of the {} ISBN-10's are invalid".format(
        invalid_numbers_count if invalid_numbers_count else "None",
        numbers_count))

Output:

ISBN 0-201-53082-1 is valid
ISBN 0-20A-53082-1 is invalid
ISBN 0-306-40615-2 is valid
ISBN 0-307-40615-9 is invalid
ISBN 0-507-40615-X is valid
2 of the 5 ISBN-10's are invalid
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Let's say:

with open("isbn_numbers.txt", "r") as fs:
    lines = fs.readlines() # will give a list 

You can iterate over lines to compute the sum, or use _sum = sum(map(int, lines)) assuming you have numbers in the txt file.

Instead of using variables here, use the list which you already have and then get the values using index.

bhansa
  • 7,282
  • 3
  • 30
  • 55