Home > Net >  How to print specific lines from a text file in python
How to print specific lines from a text file in python

Time:11-15

Ive made code that lets me write in numbers in lines, but now, out of all the numbers i get I have to make the comp. print the ones that are nicely divisible by 2 So far this is what ive got:

i = 0
x = 1
y = 0
z = 20
My_file = open("Numbers", 'w')
while i < z:
    My_file.write(str(x))
    My_file.write("\n")
    x = x   1
    i = i   1
My_file.close()
i = 0
My_file = open("Numbers", 'r')
for line in My_file:
    if int(My_file.readline(y)) % 2 == 0:
        print(My_file.readline(y))
    y = y   1

The top part work, my problem is the one int(My_file.readline(y)) % 2 == 0 is crap, it says:

invalid literal for int() with base 10: ''.

CodePudding user response:

Each line contains a line break ("2\n"), you need to remove \n before converting to number:

...
My_file = open("Numbers", 'r')
for line in My_file:
    line = line.strip() # removes all surrounding whitespaces!
    if int(line) % 2 == 0:
        print(line)
    y = y   1

Out:

2
4
6
8
10
12
14
16
18
20

CodePudding user response:

Based on previous answers, here's a fully working example:

start_value = 1
max_value = 12
filename = "numbers"

with open(filename, "w") as my_file:
    value = start_value
    while value <= max_value:
        my_file.write(f"{value}\n")
        value  = 1

with open(filename, "r") as my_file:
    lines = my_file.readlines()

for line in lines:
    line = line.strip()
    if int(line) % 2 == 0:
        print(line)

This code makes use of the "context manager" of python (the with keyword). Used with open(), it handles nicely the closing of the file.

Your error came from a \n at the end of each number. The conversion from str to int didn't work because the interpreter couldn't find out how to convert this character.

As a good practice, use meaningful variables names, even more when you ask questions here: it helps people understanding the code faster.

CodePudding user response:

Does this help:

MAXINT = 20
FILENAME = 'numbers.txt'

with open(FILENAME, 'w') as outfile:
    for i in range(1, MAXINT 1):
        outfile.write(f'{i}\n')
with open(FILENAME) as infile:
    for line in infile:
        if int(line) % 2 == 0:
            print(line, end='')

CodePudding user response:

This works:

FILE_NAME = 'Numbers.txt'
MAX_NUMBER = 20

with open(FILE_NAME, 'w') as file:
    numbers = list(map(str, range(MAX_NUMBER)))
    for n in numbers:
        file.write(n)
        file.write('\r')
with open(FILE_NAME, 'r') as file:
    for number in file:
        if int(number) % 2 == 0:
            print(number, end='')

Output:


0
2
4
6
8
10
12
14
16
18
  • Related