我正在尝试创建一个程序,该程序会在文本文件的第三列中找到353.7000
以上的值,并将其更改为353.7000
。
我知道的一个障碍是文件由列之间的2个标签分隔。这就是为什么我试图使用DictReader
来获取字段名称并将它们传递给DictWriter
,但我显然没有成功地完成这项工作。
目前程序只获取数据文件并将其设为空白。没有错误或只是将编辑后的文件留空。在几个版本中(我没有保存像doofus这样的副本)我意识到问题是它是两个制表符分隔,我得到了一个值错误。
我必须在文本文件上保留格式,因为必须由希望以该格式使用的现有程序读取。
这是数据文件的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 :(得分: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)