该程序的基础是向用户询问.txt文件并计算文件中的行数。然后程序显示文件中的行数,用户将输入一个数字以显示文件中的特定行。如果用户点击0,程序将结束。
程序运行正常,直到我在.txt文件中输入除1或最后一个行号之外的数字。程序将反复显示“输入行号,是否要退出?点击0”。
inName = input("Enter the a valid file name: ")
inputFile = open(inName, "r")
count = 0
for line in inputFile:
count = count + 1
print("The file has " + str(count) + " lines.")
inputFile.close()
while True:
try:
n = int(input("Enter a line number, want to quit? Hit 0: "))
lineno = 0
break
except ValueError:
print("Try again. Line number must be between 1 and " + str(count))
while n != 0:
if n >= 0 and n <= count:
inputFile = open(inName, "r")
for line in inputFile:
lineno = lineno + 1
if lineno == n:
print(line)
inputFile.close()
else:
print("Try again. Line number must be between 1 and " + str(count))
while True:
try:
n = int(input("Enter a line number, hit 0 to quit: "))
lineno = 0
break
except ValueError:
print("Try again. Line number must be between 1 and " + str(count))
答案 0 :(得分:1)
我不会处理您的代码中的许多问题,因为注释和答案在那里已经做得很彻底。相反,我想通过一遍又一遍地打开和关闭文件来讨论您正在创建的I / O问题。这样做很昂贵。对于几乎所有时间都在等待用户输入的程序而言,它可能不会引起注意,但是在不需要时打开和关闭文件是一个坏习惯。
我建议采用两种解决方案之一来解决此问题。如果您正在处理小的文本文件,只需将整个内容加载到内存中,例如与file.readlines()
:
inName = input("Enter the a valid file name: ")
with open(inName, "r") as file:
data = file.readlines()
count = len(data)
print(f"The file has {count} lines.")
while True:
try:
n = int(input("Enter a line number, want to quit? Hit 0: "))
except ValueError:
print(f"Try again. Line number must be between 1 and {count}")
else:
if n == 0:
break
print(data[n - 1])
对于大文件,我同意您一次仅加载一行的技术,但是您必须对此保持精明。我将打开文件一次,创建到行首的偏移量表,然后使用该表在文件中移动:
inName = input("Enter the a valid file name: ")
with open(inName, "r") as file:
table = [0]
table.extend(file.tell() for _ in file)
count = len(table) - 1 # last entry is size of file
print(f"The file has {count} lines.")
while True:
try:
n = int(input("Enter a line number, want to quit? Hit 0: "))
except ValueError:
print(f"Try again. Line number must be between 1 and {count}")
else:
if n == 0:
break
file.seek(table[n - 1])
print(file.readline()
答案 1 :(得分:0)
重构您的代码并在循环中进行一些更改,删除了您在中循环中关闭文件的部分,并将其替换为break。
如果可以尝试,请尝试:
inName = input("Enter the a valid file name: ")
inputFile = open(inName,"r")
count = 0
for line in inputFile:
count = count + 1
print("The file has "+str(count)+" lines.");
inputFile.close()
while True:
try:
n = int(input("Enter a line number, want to quit? Hit 0: "))
lineno = 0
except ValueError:
print("Try again. Line number must be between 1 and "+str(count))
if n != 0:
if n >= 0 and n <= count:
inputFile = open(inName, "r")
for line in inputFile:
if lineno == n:
print(line)
#inputFile.close()
break
else:
lineno = lineno + 1
else:
print("Try again. Line number must be between 1 and "+str(count))
else:
break