如何让Python在文本文件中写下每一行?

时间:2015-10-29 01:02:31

标签: python

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行。所以它打印出第3和第5,第7和第9。所以我只是错过了第一个。

3 个答案:

答案 0 :(得分:2)

这会跳过第一行,因为你读取它并在循环之前扔掉它。删除第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()

答案 1 :(得分:2)

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

答案 2 :(得分:0)

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)