2017-02-18 4 views
-2

pythonを使用して、私はいくつかのデータファイルを分離したい。 ファイル形式はテキストファイルであり、内部データ間にスペースが1つしかないタブはありません。 13、ファンド300テキストファイルのデータを使用して、分類を行い、Pythonで他のテキストファイルを作る

、および別のテキストファイルを保存します。ここ

は、サンプルファイル、

//test.txt 
    Class name age room fund. 
    13 A 25 B101 300 
    12 B 21 B102 200 
    9 C 22 B103 200 
    13 D 25 B102 100 
    20 E 23 B105 100 
    13 F 25 B103 300 
    11 G 25 B104 100 
    13 H 22 B101 300 

である私は、特定のデータを含む行だけを取る

クラスにしたいです。

このコードは、テキストファイルを作り、働いていた場合

//new_test.txt 
    Class name age room fund. 
    13 A 25 B101 300 
    13 F 25 B103 300 
    13 H 22 B101 300 

おかげということです。 Hk

答えて

0

これは行う必要があります。

with open('new_test.txt','w') as new_file: 
    with open('test.txt') as file: 
     print(file.readline(),end='',file=new_file) 
     for line in file: 
      arr=line.strip().split() 
      if arr[0]=='13' and arr[-1]=='300': 
       print(line,end='',file=new_file) 

ただし、質問するときにコードを含める必要があります。これは、このサイトの目的が達成されることを保証します。

+0

私はとても申し訳ありませんが、私はそれは私のコードを添付し忘れてしまいました。あなたの指摘に感謝します。 –

0

、あなたのデータをフィルタリングする場合:

def filter_data(src_file, dest_file, filters): 
    data = [] 
    with open(src_file) as read_file: 
     header = [h.lower().strip('.') for h in read_file.readline().split()] 
     for line in read_file: 
      values = line.split() 
      row = dict(zip(header, values)) 
      data.append(row) 
      for k, v in filters.items(): 
       if data and row.get(k, None) != v: 
        data.pop() 
        break 

    with open(dest_file, 'w') as write_file: 
     write_file.write(' '.join(header) + '\n') 
     for row in data: 
      write_file.write(' '.join(row.values()) + '\n') 


my_filters = { 
    "class": "13", 
    "fund": "300" 
} 

filter_data(src_file='test.txt', dest_file='new_test.txt', filters=my_filters) 
関連する問題