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



我想把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

我会将您的代码更改为:

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.strptime来解析你的日期时间,因为它更快,因为它不必猜测格式。

只需替换最后一行:

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

您可以尝试

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

最新更新