How to write every other line in a text file?

后端 未结 3 1301
温柔的废话
温柔的废话 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:23

    This skips the first line because you read it and throw it away before the loop. Delete line 4,

    line = inputFile.readline()
    

    Add change the count parity to odd with

    if count % 2 == 1:
    

    For a slightly better design, use a boolean that toggles:

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

    I tried running the program on itself:

    inputFile = open('this_file.py', 'r')
    
    count = False
    
        outputFile.write(line)
    
        if count:
    
    
    
    outputFile.close()
    

提交回复
热议问题