如何打开一个csv文件并进入循环的下一行

时间:2019-07-16 11:02:22

标签: python

我需要从csv文件的两条不同的线中查找利润/亏损。我找不到在一行上保留变量的方法,然后一旦我移到另一行上,就使用相同的变量进行比较。

我已经尝试过next()函数,但是没有运气。

导入csv

symbolCode = input("Please enter a symbol code: ")
with open("prices.csv", "r") as f:
    reader = csv.reader(f, delimiter=",")
    with open(symbolCode + ".csv", "w") as d:
        writer = csv.writer(d)
        for row in reader:
            item = 0
            item2 = 0
            if symbolCode == row[1]:
                print(row)
                writer.writerow(row)

    d.close()

我希望找到一个数字的输出,但同时使用另外两个数字减去并等于输出

1 个答案:

答案 0 :(得分:0)

您是否正在寻找类似的东西?

symbolCode = input("Please enter a symbol code: ")
with open("prices.csv", "r") as f:
    reader = csv.reader(f, delimiter=",")
    with open(symbolCode + ".csv", "w") as d:
        writer = csv.writer(d)
        previous_row = None   # <--- initialize with special (empty/none) value
        for row in reader:
            item = 0
            item2 = 0
            if symbolCode == row[1]:
                print(row)
                writer.writerow(row)
            if previous_row != None:      # <-- if we're not processing the very first row.
                if previous_row[7] < row[7]:   # <-- do your comparison with previous row
                    print("7th value is bigger now")  # <-- do something
            previous_row = row     # <-- store this row to be the previous row in the next loop iteration

请注意,我省略了d.close()行。在with语句中打开文件时不需要。除此之外,我只在您的示例中添加了行,并在这些行中标记了# <--条注释。