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