-2

Hello so i am trying to read lines from a txt file. My code is the following:

import sys
accFiletypes = '.txt'
f = None
filnavn = None
correctFiletype = False

while (correctFiletype == False):
    filnavn = input("Filename (Type exit to leave):")
    if (filnavn.endswith(accFiletypes) == True):
        try:
            f = open(filnavn, 'r')
            correctFiletype = True  
            print("File successfully opened!")
        except IOError:
            print("File is not existing")
    elif (filnavn == "exit"):
        sys.exit("Program closed")
    else:
        print("Accepted filetypes: " + accFiletypes)

line = f.readline
print(line())
print(line(2))
print(line(3))
print(line(4))
print(line(5))
print(line(6))


f.close()

This prints the following:

Filename (Type exit to leave):test.txt
File successfully opened!
0000    00000000

00
00
0000
1

0000    0

The first 10 lines in "test.txt"

0000    00000000
0000    00001
0000    00001111
0000    000099
0000    00009999
0000    0000w
0000    5927499
0000    634252
0000    6911703
0000    701068

I want it to print out the lines in the txt file but i prints something completely different. What do i do?

M3ME5
  • 57
  • 5
  • did you forgot to put () after readline? – Ezio May 18 '18 at 10:41
  • @Ezio No they just renamed it to `line`. @M3ME5 Don't pass numbers as argument, just call `line()` without arguments (but actually, use quamrana's solution). – mkrieger1 May 18 '18 at 10:43

2 Answers2

0

I think you mean:

for line in f:
    print(line)

f.close()

Or, if you meant to read the first six lines you could have done:

line = f.readline
for _ in range(6):
    print(line())

Just to note that line = f.readline makes line a bound function and the expression line() is a call to f.readline().

quamrana
  • 37,849
  • 12
  • 53
  • 71
0

As far as I know readline does not take an argument, it just gets the "next" line. See the documentation. What you want to test is:

print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())

However, I would suggest to work with with() which also handles closing the stream.

import sys
accFiletypes = '.txt'

def parse_file(f):
    with open(f, 'r') as fin:
        for line in fin:
          print(line)

correctFiletype = False
while (correctFiletype == False):
    filnavn = input("Filename (Type exit to leave):")
    if filnavn.endswith(accFiletypes):
        try:
            parse_file(filnavn)
            correctFiletype = True  
            print("File successfully opened!")
        except IOError:
            print("File is not existing")
    elif filnavn == "exit":
        sys.exit("Program closed")
    else:
        print("Accepted filetypes: " + accFiletypes)
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239