How to write every other line in a text file?

后端 未结 3 1305
温柔的废话
温柔的废话 2021-01-17 04:20
inputFile = open(\'original_text.txt\',\'r\')
outputFile = open(\'half_text.txt\',\'w\')

line = inputFile.readline()
count = 0 
for line in inputFile:
    outputFil         


        
3条回答
  •  旧巷少年郎
    2021-01-17 05:19

    use next to skip the next line. You may need to watch for a StopIteration error on the call to next(fh) if you have odd lines.

    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()
    

提交回复
热议问题