簡體   English   中英

如何在文本文件中每隔一行寫一次?

[英]How to write every other line in a text file?

inputFile = open('original_text.txt','r')
outputFile = open('half_text.txt','w')

line = inputFile.readline()
count = 0 
for line in inputFile:
    outputFile.write(line)
    count += 1
    if count % 2 == 0:
        print(line)

inputFile.close()
outputFile.close()

它一直跳過第一行。 例如,文本文件現在有10行。 因此它打印出3rd,5th,7th和9th。 所以我只是想念第一個。

這會跳過第一行,因為您已閱讀並在循環之前將其丟棄。 刪除第4行

line = inputFile.readline()

添加將計數奇偶校驗更改為奇數

if count % 2 == 1:

對於更好的設計,請使用可切換的布爾值:

count = False
for line in inputFile:
    outputFile.write(line)
    count = not count
    if count:
        print(line)

inputFile.close()
outputFile.close()

我嘗試自行運行程序:

inputFile = open('this_file.py', 'r')

count = False

    outputFile.write(line)

    if count:



outputFile.close()

使用next跳過下一行。 如果您有奇數行,則可能需要在調用next(fh)時注意StopIteration錯誤。

outputFile = open('half_text.txt','w')

with open('original_text.txt') as fh:
    for line1 in fh:
        outputFile.write(line1)
        try:
            next(fh)
        except StopIteration:
            pass

outputFile.close()

for循環將逐行遍歷文件,當您使用readline ,它將使指針在循環內前進。 因此, odd將遍及奇數行, even將遍及偶數行。

with open (path, 'r') as fi:
    for odd in fi:
        even = fi.readline()
        print ('this line is odd! :' + odd)
        print ('this line is even! :' + even)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM