简体   繁体   English

循环迭代-重写输出文件

[英]loop iteration - rewriting the output file

I currently have this code that successfully reads information from two sources and correctly formats them into an output file \\_spec_final.t15. 我目前有这段代码可以成功地从两个来源读取信息,并将它们正确格式化为输出文件\\ _spec_final.t15。 Currently the information prints one after another, but I would like it to print the information for one line/file then overwrite it with the next iteration. 当前,该信息是一个接一个地打印的,但是我希望它打印一个行/文件的信息,然后在下一次迭代中覆盖它。 Does anybody know how to do this? 有人知道怎么做这个吗?

with open('\\_spec_final.t15', 'w') as f:
    with open('info.txt', 'rt') as infofile:
        for count, line in enumerate(infofile): 
            print count
            lat = float(line[88:94]) 
            lon = float(line[119:127])
            year = int(line[190:194])
            month = int(line[195:197])
            day = int(line[198:200])
            hour = int(line[201:203])
            minute = int(line[204:206])
            second = int(line[207:209])
            dur = float(line[302:315])
            numpoints = float(line[655:660])
            fov = line[481:497] # field of view?
            sza = float(line[418:426])
            snr = 0.0000 
            roe = 6396.2 
            res = 0.5000
            lowwav = float(lowwav)
            highwav = float(highwav)
            spacebw = (highwav - lowwav)/ numpoints

            d = datetime.datetime(year, month, day, hour, minute, second)
            f.write('{:>12.5f}{:>12.5f}{:>12.5f}{:>12.5f}{:>8.1f}'.format(sza,roe,lat,lon,snr)) # line 1
            f.write("\n")
            f.write('{:>10d}{:>5d}{:>5d}{:>5d}{:>5d}{:>5d}'.format(year,month,day,hour,minute,second)) # line 2
            f.write("\n")
            f.write( ('{:%Y/%m/%d %H:%M:%S}'.format(d)) + "UT Solar Azimuth:" + ('{:>6.3f}'.format(sza)) + " Resolution:" + ('{:>6.4f}'.format(res)) + " Duration:" + ('{:>6.2f}'.format(dur))) # line 3
            f.write("\n")
            f.write('{:>21.13f}{:>26.13f}{:>24.17e}{:>12f}'.format(lowwav,highwav,spacebw,numpoints)) # line 4
            f.write("\n")

            with open(files[count], 'r') as g:
                for line in g:
                    wave_no, intensity = [float(item) for item in line.split()]
                    if lowwav <= wave_no <= highwav:
                        f.write(str(intensity) + '\n')

Open and write to the file after you read in infofile . 读入infofile后,打开并写入文件。

It will open and overwrite \\_spec_final.t15 with each iteration. 每次迭代它将打开并覆盖\\_spec_final.t15

with open('info.txt', 'rt') as infofile:   
    for count, line in enumerate(infofile):
        print count
        with open('\\_spec_final.t15', 'w') as f: 

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

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