<p>我不会用你的代码来解决大量的问题,因为注释和答案已经做了相当彻底的工作。相反,我想通过反复打开和关闭文件来讨论您正在创建的I/O问题。那样做很贵。对于一个花费几乎所有时间等待用户输入的程序来说,可能不会引起注意,但不需要就打开和关闭文件是一个坏习惯</p>
<p>我想建议两种解决方法中的一种来解决这个问题。如果您处理的是小文本文件,只需将整个文件加载到内存中,例如使用<code>file.readlines()</code>:</p>
<pre><code>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])
</code></pre>
<p>对于大文件,我同意你一次只加载一行的技术,但是你必须聪明一点。我会打开一次文件,创建一个到行首的偏移表,然后使用该表在文件中移动:</p>
<pre><code>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()
</code></pre>