如何在文本文件中每隔一行写一次? [英] How to write every other line in a text file?

查看:118
本文介绍了如何在文本文件中每隔一行写一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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行.因此,它将打印第三,第五,第七和第九.所以我只是想念第一个.

It keeps skipping the 1st line. For instance, the text file right now has 10 lines. So it prints the 3rd 5th 7th and 9th. So I'm just missing the first.

推荐答案

这会跳过第一行,因为您已阅读并在循环之前将其丢弃.删除第4行,

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

这篇关于如何在文本文件中每隔一行写一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆