2016-04-29 8 views
1

テキストファイルの第3列に353.7000以上の値を見つけて、それを353.7000に変更するプログラムを作成しようとしています。2タブ区切りのテキストファイルの値の検索と編集python 3

私が知っている障害の1つは、ファイルが列間の2つのタブで区切られていることです。だから私はDictReaderを使ってフィールド名を取得し、それをDictWriterに渡そうとしていたのですが、私は明らかにその作業に成功していません。

現在、プログラムはデータファイルを取り出して空白にします。エラーがないか、単に編集したファイルを空白のままにしておきます。いくつかのバージョンでは、私はdoofusのようなコピーを保存していませんでしたが、2つのタブ区切りで問題が認識され、値のエラーが発生しました。

テキストファイルは、その形式で必要な既存のプログラムで読み込む必要があるため、テキストファイルに書式設定を維持することが重要です。

ここにデータファイルのan exampleがあります。ここで

は、コードは次のとおりです。ここで

import os 
import sys 
import csv 

AMplateNum = input("Please Scan AM-DNA plate barcode AM******-DNA: ") 
NormFileName = AMplateNum + ".txt" 
FileToChange = "E:\\NormalizeData\\" + NormFileName 
#this prompts user to scan in AM barcode then builds the file path 

def check_value_to_edit(value): 
    if float(value) > 353.7000: 
     value = "353.7000" 
    return value 
    else: 
    return value 
#check_value_to_edit evaluates a "value" as a float and changes it to 353.7 
#if the value exceeds it 
def get_destination_dictwriter(file): 
    with open(FileToChange, 'r') as source: 
     csv_source = csv.DictReader(source, delimiter='\t') 
     fieldnames = csv_source.fieldnames 
     dictwriter = csv.DictWriter(file, fieldnames=fieldnames) 
     return dictwriter 

destination = open(FileToChange, 'w', newline='')  
csv_destination = get_destination_dictwriter(destination) 

with open(FileToChange, 'r') as source: 
     csv_source = csv.DictReader(source, delimiter='\t') 
     for row in csv_source: 
      row["Concentration"] = check_value_to_edit(row) 
      csv_destination.writerow(row) 


destination.close() 
+0

これがどのように機能しないのか詳しく説明できますか?何かエラーがありますか?何がうまくいかない?予期せぬ出力が出ますか?あなたの質問にこれを含めてください。 –

+0

複数の文字区切り文字については、あなた自身で考えると思います。私はCSVやパンダがそれらをサポートしているとは思わない。あなたが行うことができるのは、独自の特注のパーサを書くか、またはファイルをあらかじめフォーマットして、実際のファイルを変更せずにその場で1つのタブで2重のタブを置き換えて、それを読者に送ることです。 1つのタブがファイルのどこかで使用されていないことを確かめなければなりません。 [this](http://stackoverflow.com/questions/6352409/how-to-use-python-csv-module-for-splitting-double-pipe-delimited-data)の質問を参照してください。 –

答えて

1

は、私は私のコメントで述べた二つの方法があります。

from csv import DictReader 


def printdictlist(dl): 
    for i in dl: 
     print('--------------') 
     for k, v in i.items(): 
      print('{0} - {1}'.format(k, v)) 

''' Method 1 - replace double tab ''' 
with open('dbltab.csv') as f: 
    dr = DictReader((line.replace('\t\t', '\t') for line in f), delimiter='\t') 

    printdictlist(dr) 

''' Method 2 - roll your own parser ''' 
with open('dbltab.csv') as f: 
    try: 
     topline = next(f).strip().split('\t\t') 
    except StopIteration: 
     pass 

    d = [dict(zip(topline, line.strip().split('\t\t'))) for line in f] 

    printdictlist(d) 
関連する問題