读取文本文件只返回第一行
我正在尝试创建一个程序,询问用户想查看文本文件的多少行。我需要确保如果用户输入的行数超过文件中的行数,那么就打印出整个文件。
下面是我目前写的代码,但我现在遇到的问题是,无论我输入什么数字,它只打印出文本的第一行。
我使用的是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()
4 个回答
这是故意设计的。
a = file.readline()
这段代码是把文件中的一行读到变量a
里。你每次打开文件时,只读取一行(第一行)。
而这段代码:
b = file.read()
则是把整个文件的内容一次性读入到变量b
中,作为一个字符串。
如果你想读取x
行,只需要调用readline()
这个方法x
次。每次调用时,它都会返回一行字符串。你可以选择把这些行存储在一个列表里,或者把它们合并成一个字符串,或者根据需要做其他处理。
记得在用完文件后,也要调用close()
来关闭它。
也许最简单的方法是:
f = file.open('myfile.txt', 'r')
lineNum = 0
for line in f:
if lineNum < x:
print(line)
lineNum += 1
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:")]))
也许吧?
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!'
从你的问题来看,我猜你对Python还比较陌生。这里有几个概念,我会花点时间来解释一下:
首先,'with'语句创建了一个叫做'上下文'的东西。因此,跟在'with'后面的代码都是在这个上下文里执行的。我们知道在这个上下文中,文件'f'是打开的。当我们离开这个上下文时,文件会自动关闭。Python通过在进入和离开上下文时分别调用'f'的'enter'和'exit'函数来实现这一点。
Python的一个基本原则是“宁可请求原谅,也不要请求许可”。在我们的例子中,这意味着我们应该尝试不断地调用next()来读取文件,而不是先检查是否到达了文件末尾。如果真的到达了末尾,程序会抛出一个叫做StopIteration的异常,我们可以捕获这个异常来处理。
最后,xrange会生成一个'生成器'。我不打算详细讲解这个,但如果你想了解,可以参考这个很好的StackOverflow回答这里。简单来说,生成器会逐个给你数字,而不是一次性给你一大堆数字。在我们的情况下,我们并不需要整个列表,只需要在一定时间内逐个处理这些数字。
这里有一种解决你问题的方法,不过可能会有点复杂。
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")