[英]How to choose what line to print from a txt file in python
I want to print a specific line from a txt file like from a txt file like this:我想从 txt 文件中打印特定行,例如从 txt 文件中打印,如下所示:
"line number 1" “第 1 行”
"line number 2" “第 2 行”
"line number 3" “第 3 行”
I want to print line number 3 and 2 how do I do that?我想打印第 3 行和第 2 行,我该怎么做?
Let's say you want to print from start_line
to end_line
.假设您想从
start_line
打印到end_line
。 You can do as follows:您可以执行以下操作:
with open("test.txt", "r") as f:
rows = f.readlines()[start_line - 1 : end_line]
print(rows)
If start_line
is 2
and end_line
is 3
, it will print 2nd and 3rd lines of test.txt
如果
start_line
是2
并且end_line
是3
,它将打印test.txt
的第 2 行和第 3 行
This code will help you:此代码将帮助您:
from collections import deque
try:
num = int(input("Number of last lines to print:"))
except:
num = 1
a_file = open("data.txt")
lines = a_file.readlines()
for line in deque(lines, num):
print(line)
To avoid loading the whole file in memory do not use readlines
:为避免在 memory 中加载整个文件,请不要使用
readlines
:
fname = "data.txt"
skip_num = 2
with open(fname) as f:
for _ in range(skip_num):
f.readline()
for line in f:
print(line)
Cheers!干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.