繁体   English   中英

在python中写入txt

[英]Writing to txt in python

我正在将数字行从另一个文本文件写入文本文件。 运行时打印的数字看起来不错,但是当我打开输出文件时,没有写入任何内容。 想不通为什么。

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

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

我不是 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM