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
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.
- A text file should exist on the specified location
- Make sure you close the file before running the Python script.
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')
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.