繁体   English   中英

将2个列表转换为2列文本文件

[英]Turn 2 lists into 2-column text file

我想将python中的两列列表转换为两列文本文件。 第一列类型为datetime.datetime类型,另一列为float。 我在将文件写入所需格式时遇到问题。 这是我的脚本(可能草率且低效):

    from dateutil.parser import parse

    surface='EPsurface_21Oct2015Compensated.LEV'
    dataS=[]
    levelS=[]
    tempS=[]
    dateS=[]
    with open(surface,mode='r', encoding='latin_1') as fileobj:
        for line in fileobj:
            try:
                words=line.split()
                dateS.append(parse('{0} {1}'.format(words[0],words[1])))
                tempS.append(float(words[3]))
            except (TypeError,IndexError):
                pass
    filenames=[]
    #Put both columns into one list
    for i in range(len(tempS)):
        filenames.append([dateS[i],tempS[i]])
    #Convert items into string 
    for i in range(len(filenames)):
        filenames[i][0]=str(filenames[i][0])
        filenames[i][1]=str(filenames[i][1])
    for i in range(len(filenames)):
        filenames[i]=str(filenames[i]) 
    filenames=str(filenames)
    newfiles ='\n'.join(filenames)
    with open('testing.txt','w') as f:
        f.write(filenames)

输出看起来像这样:

["['2015-08-17 10:11:18', '27.572']", "['2015-08-17 10:31:18', '27.549']", "['2015-08-17 10:51:18', '32.964']", "['2015-08-17 11:11:18', '31.038']"

我希望它看起来像:

'2015-08-17 10:11:18',27.572
'2015-08-17 10:31:18', 27.549
'2015-08-17 10:51:18', 32.964

你可以试试

with open('testing.txt','w') as f:
    for (dateS, tempS) in filenames:
        # f.write("%s, %s\n" % (dateS, tempS))
        # or as the comments suggested
        f.write("{dte}, {tmp}\n".format(dte=dateS, tmp=tempS))

只需替换最后一行:

f.write('\n'.join('{0},{1}'.format(element[0], element[1]) for element in filenames))

我会将您的代码更改为:

surface='EPsurface_21Oct2015Compensated.LEV'
with open(surface,mode='r', encoding='latin_1') as fileobj, open('testing.txt', 'w') as out:
    for line in fileobj:
        try:
            words=line.split()
            dateS = str(parse('{0} {1}'.format(words[0],words[1])))
            tempS = str(float(words[3]))
            print("{0}, {1}".format(dateS, tempS), file=out)
        except (TypeError,IndexError):
            pass

如果您知道datetime字符串的格式,我也建议您使用datetime.strptime来解析日期时间,因为它更快,因为它不必猜测格式。

暂无
暂无

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

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