1

We got an exercise in class in which we need to print out the first x letters of the first y lines of a text file. That itself I managed to do with the code below, but the issue is that the exercise says "Your function should not print empty lines, e.g. lines that only contain the newline character “\n”." - Basically meaning our code should only print the first y lines which are not blank and ignore the blank lines in the counting process.

How could I change/extend my code to achieve that?

My code so far:

def print_file(name,int1,int2=None):
    file_1 = open(name, "r")

    if int2 is None:
        for line in file_1.readlines():
            print(line[:int1-1])

    else:
        lines = file_1.readlines()
        lines = lines[0:int2+1]

        for line2 in lines:
            print(line2[0:int1-1])

print(print_file("Adventures of Sherlock Holmes.txt", 10, 6))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
onlytheD
  • 11
  • 1

0 Answers0