Python 读取文本文件仅返回第一行
我正在尝试创建一个程序,询问用户希望看到多少行文本文件。我需要这样做,如果用户输入的行数超过了行数,那么在文件中,它会打印出整个文件 下面是我到目前为止的代码,但我目前遇到的问题是,无论我输入什么数字,它只打印文本的第一行 使用Python 3.4:Python 读取文本文件仅返回第一行,python,python-3.x,Python,Python 3.x,我正在尝试创建一个程序,询问用户希望看到多少行文本文件。我需要这样做,如果用户输入的行数超过了行数,那么在文件中,它会打印出整个文件 下面是我到目前为止的代码,但我目前遇到的问题是,无论我输入什么数字,它只打印文本的第一行 使用Python 3.4: def readFile(): """retrieve the file my_data.txt""" try: textFile = open("my_data.txt","r") return
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()
也许吧?就是这样
将单行读入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
f=file.open('myfile.txt','r')
lineNum=0
对于f中的行:
如果lineNum
这里有一种解决问题的方法,但可能过于复杂
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")
根据您的问题,我假设您对Python相当陌生。这里有几件事,所以我会花时间来解释:
“with”语句创建了所谓的“上下文”。因此,with缩进后面的任何内容都在该上下文中。我们知道,在此上下文中,文件“f”是打开的。当我们离开上下文时,它就关闭了。Python通过在进入和离开上下文时分别调用f的“enter”和“exit”函数来实现这一点
Python的一个标准原则是“请求原谅比请求允许更好”。他的意思是,在我们的上下文中,最好尝试对我们的文件重复调用next(),而不是检查我们是否在最后。如果我们在最后,它将抛出一个StopIteration异常,我们可以捕获它
最后,xrange生成一个“生成器”。现在,我不打算详细讨论这个问题,但是如果你愿意,有一个很好的答案。基本上,它会将数字流式传输给您,而不是将一长串数字传回给您。在我们的例子中,我们不需要整个列表,只需要迭代一段时间。如果您注意到,您调用的方法是
readline()
。它只读取一行。为什么您从未使用过readFile
的代码?
f = file.open('myfile.txt', 'r')
lineNum = 0
for line in f:
if lineNum < x:
print(line)
lineNum += 1
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!'