简体   繁体   English

读取文本文件仅返回第一行

[英]Reading text file is only returning first line

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: 使用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()
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? 也许?

That is by design . 那是设计使然

a = file.readline()

reads a single line into a . 读取单个线成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. 将整个文件读入b作为一个字符串。

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. 要阅读x线,你只需要调用readline() x很多次-每次只有一个返回该字符串时铭记。 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. 请注意,使用完文件后,还应该close()文件。

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

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")
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. 根据您的问题,我假设您是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'. “ with”语句创建所谓的“上下文”。 Therefor, anything that follows the with's indentation is within that context. 因此,with缩进之后的所有内容都在该上下文中。 We know that within this context, the file 'f' is open. 我们知道在这种情况下,文件“ f”是打开的。 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. Python通过分别在进入和离开上下文时调用f的“ enter”和“ exit”函数来实现此目的。

One of the standard principles of Python is 'It is better to ask for forgiveness than to ask for permission'. Python的标准原则之一是“请求宽恕比请求允许更好”。 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. 在我们的上下文中,他的意思是,最好尝试在文件中重复调用next(),而不是检查我们是否在末尾。 If we ARE at the end, it will throw a StopIteration exception, which we can catch. 如果我们在最后,它将抛出StopIteration异常,我们可以捕获该异常。

Lastly, xrange produces a 'generator'. 最后,xrange产生一个“生成器”。 Now, I'm not going to go into the details of this, but if you want, there is a great SO answer here . 现在,我不打算进入这一细节,但如果你想,有一个很大的SO回答这里 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. 而且,在我们的情况下,我们不需要整个列表,只需要迭代一定的时间即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM