WhyamIgettingValueErrorwheneditingmycsvfile?
I want to save the values I want in a csv file. If the file is recorded for the first time, the header names will be saved first. But when I run my code I get the following error. What do you think is the reason?
Thank you for your help
Error:
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:Anaconda3libcsv.py", line 110, in __next__
self.fieldnames
File "C:Anaconda3libcsv.py", line 97, in fieldnames
self._fieldnames = next(self.reader)
ValueError: I/O operation on closed file.
Code:
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')
回答
Since you use with in read_positions(), it automatically closes the file when it returns. Therefore, when list() tries to iterate over the return value to convert it to a list, it tries to read from a closed file.
You should change read_positions() to return the list, rather than converting it in the caller.
def read_positions():
with open('positions.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
return list(csv_reader)
THE END
二维码