2016-03-25 6 views
0

2列のリストをPythonで2列のテキストファイルに変換します。最初の列型はdatetime.datetime型で、もう1つはfloat型です。私は、私が望む形式にファイルを書き込む際に問題があります。これは私のスクリプト(それはおそらくずさんで非効率だ)です。2リストを2列のテキストファイルに変換する

["['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']" 

私のようなルックスにそれをしたい:出力は次のようになります

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 
+0

はあなたのリストのファイル名ですか? – Bahrom

+0

はい、ファイル名は1つのリストとしての日付と時刻です。 – Strak

答えて

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型を解析するためdatetime.strptimeを使用することをお勧めフォーマットを推測する必要がないため、高速です。

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

'%'形式の文字列を使用することは、私が信じるバージョン2.6のように廃止されました。代わりに '.format()'を使うべきです。 – zondo

+1

@zondo:これは間違いなく推奨されていません。形式の文字列ははるかに柔軟で、ユーザー定義の型をサポートしています。明示的な索引付けを必要としません(名前と位置指定の引数を使用します)。 Python 3は '.format'メソッドをサポートしていない' bytes'フォーマットのテンプレートを使って '%'フォーマットを可能にするサポートを追加しました。 – ShadowRanger

+0

@zondo @ShadowRangerああ、私はちょうど高速印刷のために '%'形式の文字列を使用しています.2つの変数に対しては問題ありませんが、テンプレートを読みやすくする必要がある場合にのみ使用します。多くの変数。しかし、フィードバックをありがとう、答えを編集しました。 – Bahrom

1

Rライン:私はあなたのコードを変更します

f.write('\n'.join('{0},{1}'.format(element[0], element[1]) for element in filenames)) 
関連する問題