在python中写入txt

时间:2014-02-05 22:45:09

标签: python text

我正在从另一个文本文件中将数字行写入文本文件。在运行时打印的数字看起来不错,但是当我打开输出文件时,没有写入任何内容。无法弄清楚原因。

min1=open(output1,"w")



oh_reader = open(filename, 'r')

countmin = 0

   while countmin <=300000:
        for line in oh_reader:

       #min1 
        if countmin <=60000:
            hrvalue= int(line)
            ibihr = line
            print(line)
            print(countmin)
            min1.write(ibihr)
            min1.write("\n")
            countmin = countmin + hrvalue


min1.close()

2 个答案:

答案 0 :(得分:1)

您应该使用Python的with语句来打开文件。它为您处理关闭并且通常更安全:

with open(filename, 'r') as oh_reader:

如果这是你的程序缩进的方式

min1=open(output1,"w")



oh_reader = open(filename, 'r')

countmin = 0

   while countmin <=300000:
        for line in oh_reader:
            # this is the same as having pass here
       #min1 
        if countmin <=60000:
            hrvalue= int(line)
            ibihr = line
            print(line)
            print(countmin)
            min1.write(ibihr)
            min1.write("\n")
            countmin = countmin + hrvalue
min1.close()

for循环为空,因此不会执行任何操作。解决这个问题:

min1=open(output1,"w")

oh_reader = open(filename, 'r')

countmin = 0

   while countmin <=300000:
        for line in oh_reader:
            #min1 
            if countmin <=60000:
                hrvalue= int(line)
                ibihr = line
                print(line)
                print(countmin)
                min1.write(ibihr)
                min1.write("\n")
                countmin = countmin + hrvalue
min1.close()

或者:

min1=open(output1,"w")

oh_reader = open(filename, 'r')

countmin = 0

for line in oh_reader:
    #min1 
    if countmin <=60000:
        hrvalue= int(line)
        ibihr = line
        print(line)
        print(countmin)
        min1.write(ibihr)
        min1.write("\n")
        countmin += hrvalue  # += operator is equal to a = a + b
min1.close()

答案 1 :(得分:0)

我不是100%肯定逻辑,但我认为这就是你想要的:

IN_FNAME  = 'abc.txt'
OUT_FNAME = 'def.txt'

with open(IN_FNAME) as inf, open(OUT_FNAME, 'w') as outf:
    total = 0
    for line in inf:
        val = int(line)
        total += val

        if total <= 60000:
            print('{} -> {}'.format(val, total))
            outf.write('{}\n'.format(val))
        else:
            break