在尝试写入 CSV 文件时收到以下错误。我检查了我的文件和文件夹设置,并设置了全局可用性。我该如何解决?代码也在下面。
我已经尝试过打开和关闭的文件。
File "c:\Users\toril\OneDrive\Documents\Pokemon AI\base 1 test.py", line 19, in <module> with open ('pokemontest1.csv', 'w', newline='') as csv_file: PermissionError: [Errno 13] Permission denied: 'pokemontest1.csv' from importlib.resources import Resource from string import capwords from unicodedata import name from pokemontcgsdk import RestClient from pokemontcgsdk import Card from pokemontcgsdk import Set from pokemontcgsdk import Type from pokemontcgsdk import Supertype from pokemontcgsdk import Subtype from pokemontcgsdk import Rarity from pokemontcgsdk import querybuilder from pokemontcgsdk import RestClient import csv RestClient.configure('xxxxxxxxxxxx') fields = ['Data'] with open ('pokemontest1.csv', 'w', newline='') as csv_file: Cards = Card.where(q='set.name:generations supertype:pokemon') for card in Cards: rows = [card.name, card.types, card.supertype, card.subtypes, card.number, card.rarity, card.nationalPokedexNumbers, card.id, card.set.name, card.set.series] csvwriter = csv.writer(csv_file) csvwriter.writerow(fields) csvwriter.writerows(rows)
它不起作用的原因是,一旦您退出with语句,文件就会关闭并且不再可写。
with
例如:
with open(filename) as file: contents = file.read() contents = file.read() # <-- will throw error
您的代码所做的与此等效:
csv_file = open("pokemontest2.csv", "w", newline='') Cards = Card.where(q='set.name:generations supertype:pokemon') csv_file.close() for card in Cards: rows = [card.name, card.types, card.supertype, card.subtypes, card.number, card.rarity, card.nationalPokedexNumbers, card.id, card.set.name, card.set.series] csvwriter = csv.writer(csv_file) # csv_file is no longer open csvwriter.writerow(fields) csvwriter.writerows(rows)
通过将with语句向下移动,现在处理 csv_file 的所有逻辑都在with块内。
Cards = Card.where(q='set.name:generations supertype:pokemon') for card in Cards: rows = [card.name, card.types, card.supertype, card.subtypes, card.number, card.rarity, card.nationalPokedexNumbers, card.id, card.set.name, card.set.series] with open ('pokemontest1.csv', 'w', newline='') as csv_file: csvwriter = csv.writer(csv_file) # the file is still open csvwriter.writerow(fields) csvwriter.writerows(rows)