[英]Given a line number, how to read it from a file
繼承我的代碼:
def option_a():
fixchoice = int(input("Enter: "))
file = open("firesideFixtures.txt", "r")
print(file.readlines(fixchoice))
option_a()
每當我輸入任何數字時,它總是打印相同的行。
Python有一個方便的linecache
庫來處理你的情況:
import linecache
def option_a():
line_number = int(input("Enter a line number: "))
line = linecache.getline("firesideFixtures.txt", line_number)
print(line)
readlines()的參數沒有指定從文件中讀取哪一行。 嘗試這樣的事情:
def option_a():
fixchoice = int(input("Enter: "))
with open("firesideFixtures.txt", "r") as file:
for i, line in enumerate(file, 1):
if i == fixchoice:
print(line)
break # Or return if you don't want to do anything after the loop
option_a()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.