[英]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.