[英]How to print specific lines of a file in Python
我有一个.txt
文件,我想打印第3,7,11,15行3, 7, 11, 15,...
因此,在打印第三行之后,我想在之后每隔4行打印一次。
我开始看模数运算符:
#Open the file
with open('file.txt') as file:
#Iterate through lines
for i, line in enumerate(file):
#Choose every third line in a file
if i % 3 == 0:
print(line)
#Close the file when you're done
file.close()
但这种方法打印每三行。 如果i % 3 == 1
则打印第1,4,7,10,13行等。
而不是使用模数,只需使用加法,使用要显示的第一行启动它,然后向其中添加4
next_line = 2 # Line 3 is index 2
for i, line in enumerate(file):
if i == next_line:
print(line)
next_line = next_line + 4
你的代码几乎没有问题,除了模数:你希望除法的余数为4。
with open('file.txt') as file:
for i, line in enumerate(file):
if i % 4 == 3:
print(line)
请注意,您不需要明确地close
您的文件结尾:这就是with
意为,它可以确保你的文件被关闭,无论发生什么情况。
因此,您希望每隔四次发生一次事情,这意味着模数4.尝试将if更改为if i % 4 == N:
N
数字很好。
顺便说一句,当使用with
语句时,你不必调用close()
,它会自动执行。
怎么样:
# Fetch all lines from the file
lines = open('20 - Modular OS - lang_en_vs2.srt').readlines()
# Print the 3rd line
print(lines[2])
# throw away the first 3 lines, so the modulo (below) works ok
for i in range(3):
del(lines[0])
# print every 4th line after that
for (i in range(len(lines)):
if (i > 0 and i % 4 == 0):
print(lines[i])
将每一行读入数组。 输出第3行。 然后我们需要每四行,所以通过删除前三个元素,很容易简单地对模4(“%4”)进行测试并输出该行。
x = 0
with open('file.txt') as file:
#Iterate through lines
for i, line in enumerate(file):
x += 1
#Choose every third line in a file
if x == 4:
print(line)
x = 0
#Close the file when you're done
file.close()
>>> i = 0
>>> for x in range(0, 100):
... i += 1
... if i is 4:
... print(x)
... i = 0
3 7 11 15 19 23 27 31 35 39 43 47 51 55 59 63 67 71 75 79 83 87 91 95 99
file = open('file.txt')
print(file[2])
#Iterate through lines
for i in file:
#Choose every third line in a file, beginning with 4
if i % 4 == 0:
print(i+3)
elif i % 4 == 0:
print(i)
这可行,但不是超级优雅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.