2016-04-13 11 views
1

これまでのところ、.txtファイルの特定の部分をPythonでプリントアウトすることができましたが、私の合計金額から支払った金額を引く方法は分かりません。各列の未処理の値を加算します。私が.txtファイルから得た2つの値を差し引く方法

import csv 

FILE_NAME = "paintingJobs.txt" #I use this so that the file can be used easier 
COL_HEADERS = ['Number', 'Date', 'ID', 'Total', 'Status', 'Paid'] 
NUM_COLS = len(COL_HEADERS)#This will insure that the header of each column fits into the length of the data 

# read file once to determine maximum width of data in columns 
with open(FILE_NAME) as f: 
    reader = csv.reader(f, delimiter=',') 
    # determine the maximum width of the data in each column 
    max_col_widths = [len(col_header) for col_header in COL_HEADERS] 
    for columns in reader: 
     for i, col in enumerate(columns): 
      if "A" in columns and int(columns[5]) < int(columns[3]): 
       max_col_widths[i] = max(max_col_widths[i], len(repr(col))) 
    # add 1 to each for commas 
    max_col_widths = [col_width+1 for col_width in max_col_widths] 

# read file second time to display its contents with the headers 
with open(FILE_NAME) as f: 
    reader = csv.reader(f, delimiter=',') 
    # display justified column headers 
    print(' ' + ' '.join(col_header.ljust(max_col_widths[i]) 
          for i, col_header in enumerate(COL_HEADERS))) 
    # display justified column data 
    for columns in reader: 
     if "A" in columns and int(columns[5]) < int(columns[3]): 
      print(columns)` 

これは、これまでの結果である:私は何をしたいか

Number Date   ID  Total Status Paid 
['E5345', '22/09/2015', 'C106', '815', 'A', '400'] 
['E5348', '23/09/2015', 'C109', '370', 'A', '200'] 
['E5349', '25/09/2015', 'C110', '480', 'A', '250'] 
['E5353', '28/09/2015', 'C114', '272', 'A', '200'] 
['E5355', '29/09/2015', 'C116', '530', 'A', '450'] 
['E5363', '01/10/2015', 'C124', '930', 'A', '500'] 
['E5364', '02/10/2015', 'C125', '915', 'A', '800'] 
['E5367', '03/10/2015', 'C128', '427', 'A', '350'] 
['E5373', '10/10/2015', 'C134', '1023', 'A', '550'] 

は、データのように見える合計の差があり、新しい列と有料

+0

基本的な質問は、そのコードと関係がありますか、または問題の性質を実際のプログラムから切り離すことができますか?もしそうなら、それを行い、[最小限の例](http://stackoverflow.com/help/mcve)を提供してください。 – timgeb

+0

言い換えれば、タイトルは簡単な質問ですが、なぜその質問はとても複雑ですか? – timgeb

+0

これまでのところ、CSVを.txtファイルから表示するようになったので、今度は4列目から6列目を差し引いてください。 –

答えて

0

を追加することです文字列として格納されています。それらを整数に変更しようとしましたか?あなたはこのようにします。我々が持っていると仮定します。

x="1" 

y="2" 

あなたはこのような整数に変換することができます。

x=int(x) 

y=int(x) 

次に、問題なく追加する必要があります。

+0

これを行うには、私はまだ、合計と支払いの違いである新しい列を追加する方法を知らない。 –

0

私はあなたの列幅のサイズのアプローチを破壊しましたが、あなたの望むようにファイル内のブロックが最後に変更されました。 # display justified column dataの後にすべてを置き換えてください。

for row in reader: 
    total = int(row[3]) 
    paid = int(row[5]) 
    if 'A' in row[4] and paid < total: 
     print('\t'.join((_ for _ in row)), total - paid) 

合計と有料の整数を作ることはかなり簡単です。新しいデータを表示する方法を見つけることはもう少し作業です。

+0

あなたが言ったように私はI/Oエラーが発生しました:ValueError:閉じたファイルのI/O操作。 –

関連する問題