【问题标题】:Python2.7 - Parse 1.csv, find match in # 2.csv then copy data from 2.csv and outputPython2.7 - 解析 1.csv,在 # 2.csv 中找到匹配项,然后从 2.csv 复制数据并输出
【发布时间】:2018-04-11 06:44:47
【问题描述】:

一定是我完全忽略的东西。

我正在尝试获取此脚本

import csv

in_file = open("11pmTrend.csv", 'r')
reader = csv.DictReader(in_file, delimiter= ',')
out_file = open("11pm.csv", 'w')
out_file.write("Rank,Symbol,CurrentPrice\n")
check_file = open("11pmQuote.csv", 'r')
check = csv.DictReader(check_file, delimiter=',')

trend = set()
trend_sn = dict()
for row in reader:
    trend.add(row["Symbol"])
    trend_sn[row["Symbol"]] = row["Rank"]
    print(row["Symbol"])

stocknums = dict()
for row in check:
    stocknums[row["Sym"]] = row["Price"]
    print(row["Sym"])


for product in trend:
    ref = 0
    if product in stocknums:
        if(stocknums[product] > 0):
            ref = (row["Price"])


out_file.write(str(trend_sn[product]) + ',' + str(product) + ','+ str(ref)+ "\n")

首先查看这个文件 11pmTrend.csv(平均大约 100 行),其中包含 Ranks 和 Stock/Crypto Symbols,然后捕获 Symbol,然后

Rank,Symbol
15,BTC
12,TSLA

打开第二个文件 11pmQuote.csv(平均约 9000 行),其中包含 Symbols/Prices 并获取相应的价格和

Sym,Price
TSLA,302.25
BTC,7000.76

将其输出到第三个文件 11pm.csv 中,应该如下所示:

Rank,Symbol,CurrentPrice
12,TSLA,302.25
15,BTC,7000.76

但是,我得到了这个:

Rank,Symbol,CurrentPrice
12,TSLA,7000.76
15,BTC,7000.76

它从第一个文件中获取第一行,然后将该价格附加到两行而不是迭代/循环,并输出正确的价格以匹配第二行。

我想知道我做错了什么?

【问题讨论】:

    标签: python python-2.7 csv


    【解决方案1】:

    你在引用

    for product in trend:
        ref = 0
        if product in stocknums:
            if(stocknums[product] > 0):
                ref = (row["Price"])
    

    在最后一行 row["Price"] 指的是它上面已经完成的循环,所以 row["Price"] 总是会给你最后一行的价格。

    所以应该是这样的:

    for product in trend:
        ref = 0
        if product in stocknums:
            if(stocknums[product] > 0):
                ref = (stocknums[product])
    

    因为stocknums[产品] = 价格

    我实际上不确定你想在最后一个循环中做什么,但我猜你代码中的最后一行(“out_file.write”)也在这个循环中,你没有提供工作代码样本。

    【讨论】:

    • "out_file.write" 是这样写的:Rank,Symbol,CurrentPrice 12,TSLA,7000.76 15,BTC,7000.76... 所以我希望脚本循环遍历整个符号列表(例如以上为 11pmTrend.csv)并获取每个符号的股票价格
    • 您忽略了我关于行 [“价格”] 的答案的第一部分。是的,我知道它确实会输出。但它必须在一个循环中,不是吗?它不在您的示例中,因此它不是有效的代码示例。
    • 这就是我所缺少的部分。我曾认为将其声明为 ref = (row["Price"]) 它会自行拉入该部分。没想到仅'stocknums [product] = price',原以为它还会第二次添加符号..修改了代码,现在可以使用了,非常非常感谢!!!
    • 不客气,特别是如果您接受我的回答以结束问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    相关资源
    最近更新 更多