gpt4 book ai didi

python - 为什么在编辑我的 csv 文件时出现 ValueError?

转载 作者:行者123 更新时间:2023-12-04 12:31:17 25 4
gpt4 key购买 nike

我想将我想要的值保存在 csv 文件中。如果文件是第一次录制,标题名称将首先保存。但是当我运行我的代码时,出现以下错误。你认为是什么原因?

谢谢你的帮助

错误:

Traceback (most recent call last):
File "C:/Users/Yunus/PycharmProjects/binance_test/main.py", line 40, in <module>
save_position('ETHUSDT', 'timestamp', 'datetime', 'SELL', '63', '0.034', '3244.11', '3228.44', 'WON', '93.1233223')
File "C:/Users/Yunus/PycharmProjects/binance_test/main.py", line 20, in save_position
positions = list(read_positions())
File "C:\Anaconda3\lib\csv.py", line 110, in __next__
self.fieldnames
File "C:\Anaconda3\lib\csv.py", line 97, in fieldnames
self._fieldnames = next(self.reader)
ValueError: I/O operation on closed file.

代码:

import csv


def read_positions():
with open('positions.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
return csv_reader


def save_position(pos_symbol, pos_timestamp, pos_datetime, pos_direction, pos_leverage, pos_quantity, pos_take_profit,
pos_stop_loss, pos_result, usdt_balance):

with open('positions.csv', 'a', newline='') as csv_file:

fieldnames = ['pos_symbol', 'pos_timestamp', 'pos_datetime', 'pos_direction', 'pos_leverage', 'pos_quantity',
'pos_take_profit', 'pos_stop_loss', 'pos_result', 'usdt_balance']

csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

positions = list(read_positions())

if len(positions) < 1:

csv_writer.writeheader()

csv_writer.writerow({
'pos_symbol':pos_symbol,
'pos_timestamp':pos_timestamp,
'pos_datetime':pos_datetime,
'pos_direction':pos_direction,
'pos_leverage':pos_leverage,
'pos_quantity':pos_quantity,
'pos_take_profit':pos_take_profit,
'pos_stop_loss':pos_stop_loss,
'pos_result':pos_result,
'usdt_balance':usdt_balance
})


save_position('ETHUSDT', 'timestamp', 'datetime', 'SELL', '63', '0.034', '3244.11', '3228.44', 'WON', '93.1233223')

最佳答案

由于您在 read_positions() 中使用了 with,它会在返回时自动关闭文件。因此,当 list() 尝试迭代返回值以将其转换为列表时,它会尝试从已关闭的文件中读取。

您应该更改 read_positions() 以返回列表,而不是在调用者中转换它。

def read_positions():
with open('positions.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
return list(csv_reader)

关于python - 为什么在编辑我的 csv 文件时出现 ValueError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68877243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com