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

时间:2016-03-25 22:58:03

标签: python datetime

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

    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

3 个答案:

答案 0 :(得分:1)

你可以尝试

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

答案 1 :(得分:1)

只需替换最后一行:

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

答案 2 :(得分:1)

我会将您的代码更改为:

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