共計 452 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 open()
函數打開文件,并使用 readlines()
方法讀取文件的所有行,然后通過索引來獲取第 n 行。下面是一個簡單的示例:
def read_line(file_path, n):
with open(file_path, 'r') as file:
lines = file.readlines()
if n <= len(lines):
return lines[n-1]
else:
return "Line does not exist."
file_path = 'example.txt' # 文件路徑
line_number = 3 # 第 3 行
line = read_line(file_path, line_number)
print(line)
請將 file_path
替換為你要讀取的文件的路徑,將 line_number
替換為你要讀取的行數。運行代碼后,將會打印出第 n 行的內容。如果指定的行數超過文件的總行數,則會打印出 "Line does not exist."。
丸趣 TV 網 – 提供最優質的資源集合!
正文完