IPython控制台太小无法打印数据,如何写入文件?

IPython console too small to print data, how to write to file?

我正在使用 Spyder (Python 2.7) 分析一些文件,并在 IPython 控制台中打印出派生值。这适用于较小的数据文件夹,因为所有结果都可以打印在控制台中。我是 python 初学者,所以我不确定如何调整下面的代码以将这些结果写入文件(txt 或 csv),而不是将它们打印到 IPython 控制台。

对于每个文件,数据输出应该如下所示,尽管打印在一行上也可以。理想情况下,我不想将所有数据附加到同一个输出文件。有没有一种简单的方法可以将包含 print 命令的行修改为写入文件的命令?我对 csv.DictWriter 有一些经验,但我不确定在这种情况下如何使用它。

1063.3187872 ,
-243.615246702 ,
867.312033099 ,
3301.47950932 ,
10813.0 ,
-3.86140412292 ,
14.3743086525 ,
27.4415273499 ,
10.5395891182 ,
0.0 ,
53.0 ,
0.0 ,
0.0 ,a

我的代码如下:

import sharppy
import sharppy.sharptab.profile as profile
import sharppy.sharptab.interp as interp
import sharppy.sharptab.winds as winds
import sharppy.sharptab.utils as utils
import sharppy.sharptab.params as params
import sharppy.sharptab.thermo as thermo
import numpy as np
from StringIO import StringIO
import glob
import os


os.chdir('X:/nonseabreezestormdays')
for file in glob.glob("*.oax"):
    spc_file = open(file, 'r').read()


    def parseSPC(spc_file):
        ## read in the file
        data = np.array([l.strip() for l in spc_file.split('\n')])

        ## necessary index points
        title_idx = np.where( data == '%TITLE%')[0][0]
        start_idx = np.where( data == '%RAW%' )[0] + 1
        finish_idx = np.where( data == '%END%')[0]

        ## create the plot title
        data_header = data[title_idx + 1].split()
        location = data_header[0]
        time = data_header[1][:11]

        ## put it all together for StringIO
        full_data = '\n'.join(data[start_idx : finish_idx][:])
        sound_data = StringIO( full_data )

        ## read the data into arrays
        p, h, T, Td, wdir, wspd = np.genfromtxt( sound_data, delimiter=',', comments="%", unpack=True )

        return p, h, T, Td, wdir, wspd

    pres, hght, tmpc, dwpc, wdir, wspd = parseSPC(spc_file)

    prof = profile.create_profile(profile='default', pres=pres, hght=hght, tmpc=tmpc, \
                                        dwpc=dwpc, wspd=wspd, wdir=wdir, missing=-9999, strictQC=True)
    msl_hght = prof.hght[prof.sfc] # Grab the surface height value
    #print "SURFACE HEIGHT (m MSL):",msl_hght
    agl_hght = interp.to_agl(prof, msl_hght) # Converts to AGL
    #print "SURFACE HEIGHT (m AGL):", agl_hght
    msl_hght = interp.to_msl(prof, agl_hght) # Converts to MSL
    #print "SURFACE HEIGHT (m MSL):",msl_hght
    sfcpcl = params.parcelx( prof, flag=1 ) # Surface Parcel
    fcstpcl = params.parcelx( prof, flag=2 ) # Forecast Parcel
    mupcl = params.parcelx( prof, flag=3 ) # Most-Unstable Parcel
    mlpcl = params.parcelx( prof, flag=4 ) # 100 mb Mean Layer Parcel
    print mupcl.bplus, "," # J/kg
    print mupcl.bminus, "," # J/kg
    print mupcl.lclhght, "," # meters AGL
    print mupcl.lfchght, "," # meters AGL
    print mupcl.elhght, "," # meters AGL
    print mupcl.li5, "," # C
    sfc = prof.pres[prof.sfc]
    p3km = interp.pres(prof, interp.to_msl(prof, 3000.))
    p6km = interp.pres(prof, interp.to_msl(prof, 6000.))
    p1km = interp.pres(prof, interp.to_msl(prof, 1000.))
    mean_3km = winds.mean_wind(prof, pbot=sfc, ptop=p3km)
    sfc_6km_shear = winds.wind_shear(prof, pbot=sfc, ptop=p6km)
    sfc_3km_shear = winds.wind_shear(prof, pbot=sfc, ptop=p3km)
    sfc_1km_shear = winds.wind_shear(prof, pbot=sfc, ptop=p1km)
    print utils.comp2vec(mean_3km[0], mean_3km[1])[1], ","
    print utils.comp2vec(sfc_6km_shear[0], sfc_6km_shear[1])[1], ","
    srwind = params.bunkers_storm_motion(prof)
    #print "Bunker's Storm Motion (right-mover) [deg,kts]:", utils.comp2vec(srwind[0], srwind[1])
    #print "Bunker's Storm Motion (left-mover) [deg,kts]:", utils.comp2vec(srwind[2], srwind[3])
    srh3km = winds.helicity(prof, 0, 3000., stu = srwind[0], stv = srwind[1])
    srh1km = winds.helicity(prof, 0, 1000., stu = srwind[0], stv = srwind[1])
    print srh3km[0], ","
    stp_fixed = params.stp_fixed(sfcpcl.bplus, sfcpcl.lclhght, srh1km[0], utils.comp2vec(sfc_6km_shear[0], sfc_6km_shear[1])[1])
    ship = params.ship(prof)
    eff_inflow = params.effective_inflow_layer(prof)
    ebot_hght = interp.to_agl(prof, interp.hght(prof, eff_inflow[0]))
    etop_hght = interp.to_agl(prof, interp.hght(prof, eff_inflow[1]))
    print ebot_hght, ","
    print etop_hght, ","
    effective_srh = winds.helicity(prof, ebot_hght, etop_hght, stu = srwind[0], stv = srwind[1])
    print effective_srh[0], ","
    ebwd = winds.wind_shear(prof, pbot=eff_inflow[0], ptop=eff_inflow[1])
    ebwspd = utils.mag( ebwd[0], ebwd[1] )
    print ebwspd, ",a"
    scp = params.scp(mupcl.bplus, effective_srh[0], ebwspd)
    stp_cin = params.stp_cin(mlpcl.bplus, effective_srh[0], ebwspd, mlpcl.lclhght, mlpcl.bminus

您可以使用 file 对象的内置 write 方法写入 Python 中的文件。首先你需要打开文件,所以使用

with open(filename, 'w') as file:

下面的所有内容都应缩进。然后只需将所有打印语句从 print x, y 更改为 file.write(str(x) + str(y) + '\n')

将您的输出附加到文件中:

f = open('myfile.txt','a')
f.write(mupcl.bplus+ ",")
f.write(mupcl.bminus+ ",")
f.write(mupcl.lclhght+ ",")
f.write(mupcl.elhght+ ",")
f.write(mupcl.li5+ ",")
# do this as long as you need to
##f.seek(0,0) # return to the beginning of the file if you need to
f.close() # close the file handle

您可以在每一行的末尾添加一个 \n 以获取文件中不同行上写入的所有这些行。