When I run the following code I get an error named permission denied:
f=open('C:/Windows/System32/azm.txt','w')
f.write('+989193667998')
f.close()
On Windows, use backslashes instead of slashes to specify file paths:
f = open(r'c:\windows\system32\azm.txt', 'w')
And since you're trying to write to a system directory, make sure you run your code as Administrator.
Related
I am trying to simply build a program, which reads another file. When I try to run the code I get the error mentioned in the topic. I've already tried to take the full path, but it wasn't working.
Do you have any ideas to solve the problem?
file = open("Text.txt")
vari = file.read()
print(vari)
When you're launching from a command line, the current working directory may not be the same as the home directory of your top-level file (i.e., the directory where your program file resides).
If you run it in cmd.exe (Command Prompt), then path to file "Text.txt" will be searched for in the directory currently opened in the Command line. Usually, C:\Users\[user]\ is the default working directory on Windows.
You need to run your program using Python interpreter/Py Laucher, that is usually opened on double click on *.py top-level program file or simply change the current directory in Command prompt with cd <TOP_LEVEL_FILE_DIR>.
You have to add the full path above file = open("Text.txt") line to indicate where this file is located. Adding the full path to the open(/path/to/where/this/text.txt) like an example is required in this case (so even if your main program is not in the same directory as the file you're trying to open, it will still work). There are many examples on SO, that show how this can be achieved.
Try the following code,
To open the file, use the built-in open() function.
fileLocation = open("C:/Users/Desktop/Text.txt", "r")
vari = fileLocation.read()
print(vari)
"r": read file "w": write file
It will read the file and will display the contents of the file.
Make sure you use the forward slash in the path.
I have a python 3 code:
system_name = 'myName'
path_perf_folder = os.path.dirname(sys.argv[0]) + '/' + system_name + '_test/'
try:
coriginal_umask = os.umask(0)
os.makedirs(path_perf_folder, 0o755)
finally:
os.umask(original_umask)
The code runs perfectly from python console (running directly os.makedirs command without permission and umask stuff), but when I run from Linux Centos 7.0 terminal or MacOS 10.14.1 terminal it does not work.
I have tried different permissions al well (0o770 and 0o777) but all the time my error is:
File "performance_maker.py", line 130, in <module>
os.makedirs(path_perf_folder, 0o755)
File "/shared/centos7/python/3.7.0/lib/python3.7/os.py", line 221, in
makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/myName_test/'
The umask part I c/p from a stackoverflow question but it does not work for me
here is the link
Thanks!
os.path.dirname(sys.argv[0]) will only be a nonempty string if sys.argv[0] has a path separator (i.e. '/' for unix-like systems) character in it. Using string operations to construct the path like you do means that you'll try to create the directory under /, which you probably don't have write access to. Instead, you should use os.path.join to construct your path, so that empty strings get handled properly and you get the relative path you want.
When run from the command line, your script is probably getting only the filename of the script, not the full path. Therefore, when run at the command line, your script is attempting to mkdir in the root ("/") folder. See below for a quick script you can run to see how your system works.
import os, sys
dirname_out = os.path.dirname(sys.argv[0])
print('sys.argv[0] is {}'.format(sys.argv[0])) # See difference from REPL and when run as script
print('cwd is {}'.format(os.getcwd())) # Might be what you want
print('dirname is: {}'.format(dirname_out))
print('dirname of cwd is: {}'.format(os.path.dirname(os.getcwd()))) # Not recommended
Depending on how you want your script to operate, your solution will vary. I am not sure of your desired outcome as you did not supply the input when you executed your script.
If you want to run the script and always make the new directory in the same directory you ran the script, you probably want to us "os.getcwd()" for creating the base dir.
If you want to provide the location to create the directory, then you probably want to pass the directory to the script by checking, parsing, and constructing from sys.argv[1].
I want to run python command as follows, without the whole path of pyahp or other scripts. It reported the error. I have to add the whole path, ie .../site_packages/ that is tedious. How can I run it directly?
[~] python pyahp
/Library/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python: can't open file 'pyahp':
[Errno 2] No such file or directory
I trid to add pythonpath, however it failed.
export
PYTHONPATH="$PYTHONPATH:/Library/Frameworks/Python.framework/Versions/3.6/lib"
I'm trying to open a file in python. Simple enough. The script that I am using is the same directory as my code, so I just use
myfile = open('file.txt', 'r')
This worked fine before, but now I am getting the error 'No such file or directory' (Errno2)
Why is this happening? I've used OS to check if I am in the right directory, and it is fine. What is python doing differently now than it did 20 minutes ago, when it found the file perfectly??
Assuming the file you are trying to open/read has appropriate permissions, the behavior is defined based on how you are invoking your python program. Let's assume your code and the file.txt are in ~/Desktop
If you are in ~/Desktop and do a python code.py your code will work fine. But if you are in say your home folder - ~ and do a python ~/Desktop/code.py then the python interpreter assumes your current working directory to be ~ and will return the error:
IOError: [Errno 2] No such file or directory: 'file.txt'
since it will not find file.txt in ~
Further, in the context of the given example:
os.getcwd()
returns the absolute path of your home directory and
os.path.realpath(__file__)
returns the absolute path of your python source file
Is it possible you are typing the name wrong, eg "test.fna" versus "test.fna.txt"?
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 assume python will create it on its own):
fout = open("newfile.dat", "w")
fout.write(abc)
First, will python create a newfile.dat on its own? Secondly, it's giving me this error:
IOError: [Errno 13] Permission denied: 'newfile.dat'
What's wrong here?
Please close the file if its still open on your computer, then try running the python code.
I hope it works
This also happens when you attempt to create a file with the same name as a directory:
import os
conflict = 'conflict'
# Create a directory with a given name
try:
os.makedirs(conflict)
except OSError:
if not os.path.isdir(conflict):
raise
# Attempt to create a file with the same name
file = open(conflict, 'w+')
Result:
IOError: [Errno 13] Permission denied: 'conflict'
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')
Permission denied simply means the system is not having permission to write the file to that folder. Give permissions to the folder using "sudo chmod 777 " from terminal and try to run it. It worked for me.
I write python script with IDLE3.8(python 3.8.0)
I have solved this question:
if the path is
shelve.open('C:\\database.dat')
it will be
PermissionError: [Errno 13] Permission denied: 'C:\\database.dat.dat'.
But when I test to set the path as
shelve.open('E:\\database.dat')
That is OK!!!
Then I test all the drive(such as C,D,F...) on my computer,Only when the Path set in Disk
C:\\
will get the permission denied error.
So I think this is a protect path in windows to avoid python script to change or read files in system Disk(Disk C)
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.
To answer your first question: yes, if the file is not there Python will create it.
Secondly, the user (yourself) running the python script doesn't have write privileges to create a file in the directory.
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.
Make sure that you have write permissions for that directory you were trying to create file by properties