1

I'm trying to create a program that asks a user how many lines of the text file they want to see. I need to make it so if the user enters more than the number of lines, then I have in the file that it prints out the entire file.

Below is the code I have so far but the problem I am currently having is it only prints out the first line of the text no matter what number I enter.

Using Python 3.4:

def readFile(): 
    """retrieve the file my_data.txt"""
    try:
        textFile = open("my_data.txt","r")
        return textFile
    except:
        print("The file does not exist")
        return

def readLines():    
    textFile = open("my_data.txt","r")  
    file_lines = textFile.readline()        
    print(file_lines)

#main
while True:
    cmd = int(input("\nEnter the number of lines you would like to read: "))    
    readLines()
OJFord
  • 10,522
  • 8
  • 64
  • 98
user3769455
  • 15
  • 1
  • 4

4 Answers4

0
def get_user_int(prompt):
   while True:
      try: 
         return int(input(prompt))
      except ValueError:
         print("ERROR WITH INPUT!")

print("\n".join(textFile.readlines()[:get_user_int("Enter # of Lines to view:")]))

maybe?

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

That is by design.

a = file.readline()

reads a single line into a. You are opening the file, and reading one line (the first) each time.

It is:

b = file.read()

that reads the whole file into b, as one string.

To read x lines, you just need to call readline() x many times - bearing in mind each time it is just one string that is returned. It is up to you to store them in a list or join them into a single string, or whatever is most appropriate.

Note that you should also close() the file when you are done with it.

Perhaps the most simple techinque would be:

f = file.open('myfile.txt', 'r')
lineNum = 0
for line in f:
    if lineNum < x:
        print(line)
        lineNum += 1
OJFord
  • 10,522
  • 8
  • 64
  • 98
0

Here is a way to solve you problem, but it might be overly complex.

import os
import sys

def readFile(file_name):
    # check if the file exists
    if not os.path.exists(file_name):
        sys.stderr.write("Error: '%s' does not exist"%file_name)
        # quit
        sys.exit(1)

    textFile = open(file_name, "r")
    file_lines = textFile.read()
    # split the lines into a list
    file_lines = file_lines.split("\n")
    textFile.close()

    is_number = False
    while not is_number:
        lines_to_read = input("Enter the number of lines you would like to read: ")
        # check if the input is a number
        is_number = lines_to_read.isdigit()
        if not is_number:
            print("Error: input is not number")

    lines_to_read = int(lines_to_read)
    if lines_to_read > len(file_lines):
        lines_to_read = len(file_lines)

    # read the first n lines
    file_lines = file_lines[0:lines_to_read]
    file_lines = "\n".join(file_lines)
    print(file_lines)

readFile("my_data.txt")
kyle k
  • 5,134
  • 10
  • 31
  • 45
0
def read_file(file_name, num):
    with open(file_name, 'r') as f:
        try:
            for i in xrange(num):
                print f.next()
        except StopIteration:
            print 'You went to far!'

From your question, I'm assuming you're fairly new to Python. There are a few things going on here, so I'll take the time to explain them:

The 'with' statement creates what is known as a 'context'. Therefor, anything that follows the with's indentation is within that context. We know that within this context, the file 'f' is open. When we leave the context, it closes. Python does this by calling f's 'enter' and 'exit' functions when it enters and leaves the context, respectively.

One of the standard principles of Python is 'It is better to ask for forgiveness than to ask for permission'. What his means in our context, is that it is better to try to repeatedly call next() on our file, than to check if we are at the end. If we ARE at the end, it will throw a StopIteration exception, which we can catch.

Lastly, xrange produces a 'generator'. Now, I'm not going to go into the details of this, but if you want, there is a great SO answer here. Basically, it streams you the number, rather than passing you back a long list of them. And, in our case, we never need the whole list, we just need to iterate for a certain duration.

Community
  • 1
  • 1
nobillygreen
  • 1,548
  • 5
  • 19
  • 27