我在嘗試寫入 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)
uj5u.com熱心網友回復:
它不起作用的原因是,一旦您退出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)
uj5u.com熱心網友回復:
三件事解決了它:
- 將檔案移到 VS 代碼之外。
- 關閉檔案,更改名稱并允許它重寫一個新檔案。
- 在我的代碼中將 With Open 陳述句向下移動。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/489298.html
標籤:Python python-3.x
上一篇:查找每行具有最新日期的列名-idxmax回傳TypeError和datetime
下一篇:Python嵌套groupby
