Permission denied error while writing to a file in Python

后端 未结 9 1876
萌比男神i
萌比男神i 2020-12-17 08:48

I want to create a file and write some integer data to it in python. For example, I have a variable abc = 3 and I am trying to write it to a file (which doesn\'t exist and I

相关标签:
9条回答
  • 2020-12-17 09:20

    In order to write on a file by using a Python script, you would have to create a text file first. Example A file such as C:/logs/logs.txt should exist. Only then the following code works:

    logfile=open(r"C:/logs/logs.txt",'w')
    

    So summary.

    1. A text file should exist on the specified location
    2. Make sure you close the file before running the Python script.
    0 讨论(0)
  • 2020-12-17 09:33

    I've had the same issue using the cmd (windows command line) like this

    C:\Windows\System32> "G:\my folder\myProgram.py"
    

    Where inside the python file something like this

    myfile = open('myOutput.txt', 'w')
    

    The error was that when you don't use a full path, python would use your current directory, and because the default directory on cmd is

    C:\Windows\System32 
    

    that won't work, as it seems to be write-protected and needs permission & confirmation form an administrator

    Instead, you should use full paths, for example:

    myfile = open('G:\my folder\myOutput.txt', 'w')
    
    0 讨论(0)
  • 2020-12-17 09:35

    If you are executing the python script via terminal pass --user to provide admin permissions.

    Worked for me!

    If you are using windows run the file as admin.

    If you are executing via cmd, run cmd as admin and execute the python script.

    0 讨论(0)
提交回复
热议问题