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

标签 python csv

我想将我想要的值保存在 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/

相关文章:

python - 从 csv 行中删除双引号

sql - 根据第一列合并CSV表行 - sqlite

python - 导入错误 : Module "whitenoise.middleware" does not define a "WhiteNoiseMiddleWare" attribute/class

python - 创建表时修改DEFAULT子句

python - 按列将嵌套列表写入 csv

javascript - 将保存 CSV 数据的数组合并到一个对象数组中

php - 使用 laravel 将整个表格导出到 CSV

python - Tkinter .after 方法卡住窗口?

python - Python 脚本中的 Maya 崩溃

c++ - 编译cgal-python