Python权限错误:[错误13]写入CSV文件

b4wnujal  于 2023-06-19  发布在  Python
关注(0)|答案(2)|浏览(188)

我是一个新手,当涉及到Python编程。感谢下面的任何指导。
在Windows上运行python游戏应用程序并获得以下错误:
许可错误:[Errno 13] Permission denied:'c:\smith\python\game_tallies.csv' [3328]由于未处理的异常,无法执行脚本'Blackjack 4'!
下面是相关代码。谢谢

更新游戏统计csv文件

file_name = r'c:\smith\python\game_tallies.csv'

with open(file_name, mode='w', newline="", encoding='utf-8') as tally_file:
    tally_writer = csv.writer(tally_file, delimiter=',', quotechar='"',   
            quoting=csv.QUOTE_MINIMAL)
    tally_writer.writerow(['Banker Total','Player Total','Total Draws','Total 
            Surrenders'])
            tally_writer.writerow([str(banker_total_score), str(player_total_score),  
            str(draw_total), str(surrender_total)])

csv_file.close()
tally_file.close()

我已经尝试更改csv文件的权限,但没有运气。

jaxagkaj

jaxagkaj1#

发生这种情况是因为您作为没有打开文件权限的用户运行python脚本(这就是为什么它说permission denied)。
检查文件权限和正在运行脚本的用户的权限。

piok6c0g

piok6c0g2#

您可以使用相对文件路径,而不是使用像'c:\smith\python\game_tallies. csv'这样的绝对文件路径。将'game_tallies.csv'文件放在Python脚本所在的目录中,然后修改代码如下:

import os

# Get the directory of the current script
script_dir = os.path.dirname(os.path.abspath(__file__))

# Construct the file path relative to the script directory
file_name = os.path.join(script_dir, 'game_tallies.csv')

# Rest of your code remains the same

使用相对文件路径可确保脚本将在与脚本相同的目录中查找文件,而不管其绝对位置如何。
尝试这些建议,希望您能够解决权限错误并成功写入CSV文件。

相关问题