即使没有在代码中使用str,也无法调用'str'对象

时间:2018-11-11 18:57:06

标签: python-3.x pandas csv

我收到此错误。如何解决呢?请帮帮我。

# Import pandas
import pandas as pd
import csv

# Load csv
#df = pd.read_csv("D:\Harsha\Trading\cm14SEP2018bhav.csv")

# Read in csv file
#for row in csv.reader(open("D:\Harsha\Trading\cm14SEP2018bhav.csv"), delimiter=','):
      #print(row)
#import csv

infile = 'H:\cm09NOV2018bhav.csv'
outfile = 'H:\output_cm09NOV2018bhav.csv'

wfh = open (outfile, 'w')

with open(infile, 'r') as fh:

    reader = csv.DictReader(fh, delimiter=',')
    wfh.write("{},{},{},{},{},{},{}".format("SYMBOL", "OPEN", "HIGH", "LOW", "CLOSE", "ISIN", "TOTTRDQTY", "STATUS"))
    wfh.write("\n")
    for row in reader:
        symbol = row['SYMBOL']
        series = row['SERIES']
        open = row['OPEN']
        high = row['HIGH']
        low = row['LOW']
        close = row['CLOSE']
        last = row['LAST']
        prevclose = row['PREVCLOSE']
        tottrdqty = row['TOTTRDQTY']
        tottrdval = row['TOTTRDVAL']
        timestamp = row['TIMESTAMP']
        totaltrades = row['TOTALTRADES']
        isin = row['ISIN']
        print(low.rstrip())
        if float(high.rstrip()) in [9,25,49,81,121,169,225,289,301,441,529,625]:
            wfh.write("{},{},{},{},{},{},{},{}".format(symbol, open, high, low, close, isin, tottrdqty, "SELL"))
            wfh.write("\n")
        elif float(low.rstrip()) in [9,25,49,81,121,169,225,289,301,441,529,625]:
            wfh.write("{},{},{},{},{},{},{},{}".format(symbol, open, high, low, close, isin, tottrdqty, "BUY"))
            wfh.write("\n")
        elif float(close.rstrip()) in [9,25,49,81,121,169,225,289,301,441,529,625]:
            wfh.write("{},{},{},{},{},{},{},{}".format(symbol, open, high, low, close, isin, tottrdqty, "CLOSE PRICE"))
            wfh.write("\n")
        elif float(open.rstrip()) in [9,25,49,81,121,169,225,289,301,441,529,625]:
            wfh.write("{},{},{},{},{},{},{},{}".format(symbol, open, high, low, close, isin, tottrdqty, "OPEN PRICE"))
            wfh.write("\n")

#wfh._archive.close()
wfh.close()

我没有在代码中使用str。为什么会出现此错误?

2 个答案:

答案 0 :(得分:0)

我相信在使用格式打印时,应避免在格式参数中添加字符串值

因此所有写入wfh文件的代码如下:

wfh.write("{},{},{},{},{},{},{},{}".format(symbol, open, high, low, close, isin, tottrdqty, "SELL"))

需要更改为:

wfh.write("{},{},{},{},{},{},{},SELL".format(symbol, open, high, low, close, isin, tottrdqty))
# here 'Sell' is a part of the print argument which is already under quotes.

答案 1 :(得分:0)

找到了:

        open = row['OPEN']

此代码将row['OPEN']的内容重新分配给python关键字open(用于打开文件),这意味着当您调用open时,您正在调用str对象,而不是函数。

考虑这一点:

print(type(open))
# <class 'builtin_function_or_method'>
open = 'hello, world'
print(type(open))
# print(type('hello, world'))

您不能再将其“调用”为打开状态(即open('file.txt', 'r')),因为它是字符串,而不是函数。