在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."。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: linux自带python能进行代码调试吗