PermissionError Errno 13 Permission denied - python

I am trying to read a directory which contains html files with python. The code I am using is this:
import os
f = open(r"C:\Users\Grty\Desktop\de", "w+")
for filename in os.listdir(os.getcwd()):
content = f.read()
print (filename, len(content))
The problem is I cant access the directory. I have tried different locations but the problem persists. I have also done the relative chmod 777 (Using windows 10) and still nothing. I enabled sharing with everyone, giving read/write permissions to everyone and also disabled the "read only" (which somehow is being re-enabled itself). I have also run the cmd as an admin and still no progress. Anyone got an idea of how to overcome this?

You are trying to open a folder for writing:
f = open(r"C:\Users\Grty\Desktop\de", "w+")
But this is a folder, which can't be opened using open() even in "r" mode, because it isn't a file, and if you try, Windows will say access denied. As you get each filename, open that:
for filename in os.listdir(os.getcwd()):
with open(filename) as f:
content = f.read()

Related

Intermittent "No such file or directory" and permission errors when opening files (in a loop) on mounted FTP drive (linux)? Sync issue?

Getting errors like
FileNotFoundError: [Errno 2] No such file or directory: '/path/to/files/file.pdf'
when trying to loop through and open files in a mounted FTP drive (mounted via curlftpfs 'myuser:mypassword'#MY.SERVER.IP /path/to/files). I suspect sync issues, as the mounted drive is from another server on our network.
I can see that the file is there, can open it manually, can ls '/path/to/files/file.pdf' to see the file, but when executing...
FILES = os.listdir('/path/to/files')
FILES.sort()
.
.
.
for file in FILES:
with open(os.path.join('/path/to/files', 'file.pdf'), 'rb') as fd:
do stuff
... I sometimes get the FileNotFOundError.
More confusing, I can actually open this file (using the same path string that the error message tells me is not a file or directory) separately by just starting a python interactive shell and run something like...
fd = open('/path/to/files/file.pdf', 'rb')
fd.read()
...so IDK what the issue could be when reading it in a list of files.
Any debugging ideas or ideas of what could be causing this? Could there be some kind of timing/sync issues between reading the files on the mounted FTP drive vs the script that is running locally (and how to fix)?
* UPDATE:
Oddly, printing the target path before trying to open the file like...
print(os.path.join('/path/to/files', 'file.pdf'))
time.sleep(2) # giving even more time after initial access
with open(os.path.join('/path/to/files', 'file.pdf'), 'rb') as fd:
do stuff
...seems to help (kinda). Now also randomly throws PermissionErrors for random files that I had no problem reading before (still occasionally throws FileNotFoundErrors) and that I can actually open when accessing individually in python interactive shell. Makes me moreso think it is some kind of sync issue. Will need to investigate more.
It seems that os.path is a module, it will return an error if you use it like os.path('/path/to/files/file.pdf')
But I think it's not the cause of FileNotFOundError.

Python save file to root subfolder

I am trying to set the folder_out to the subfolder where the source .csv is found.
So I have many folders and subfolders in the main Processing folder.
I want to save the the .csv file in the same folder as where it has found the file.
When I use the root, with pathlib, is that possible?
And, I am getting now back IOError: [Errno 13] Permission denied: 'D:\Processing\DG_Boeblingen-..... etc.
So it found the file, but can't write.
I am in Python 2.7 and using 'wb' to write.
how I set the Path and rb an wb, is using wb and rb, correct?
folder_in = Path(r'D:\Processing')
folder_out = Path(r'.')
folder_in_traj = Path(r'D:\Processing')
folder_out_traj = Path(r'.')
for incsv in folder_in.iterdir():
outcsv = folder_out.joinpath('0new'+incsv.name)
with open(str(incsv), 'rb') as input, open(str(outcsv), 'wb') as output:
You are trying to save a file in root directory for which you would need sudo prviliges so if you execute the python script as super user then you should not see this issue.
I am kind of confused as to what you are trying to do here. Are you trying to output the CSV to root? In that case I think you are using Path(r'root') wrong. If you look at the documentation for pathlib, there is a class called PurePath with a method called root. You can use this to return the root.
Passing in root to Path will just return root as the path. You can try using . instead of root which might resolve to the root.

IOError: [Errno 13] Permission denied

I have this piece of code to create a .json file to store python data. When i run it in my server i get this error:
IOError: [Errno 13] Permission denied: 'juliodantas2015.json' at line with open(output_file, 'wb') as fp:
Python code:
fich_input='juliodantas2015.txt'
output_file= fich_input.strip('.txt')+'.json'
import json
with open(output_file, 'wb') as fp:
json.dump('yes', fp)
In command line i typed chmod 777 *.py but still not working. How can i fix this ?
I had a similar problem. I was attempting to have a file written every time a user visits a website.
The problem ended up being twofold.
1: the permissions were not set correctly
2: I attempted to use
f = open(r"newfile.txt","w+") (Wrong)
After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+") (Right)
IOError: [Errno 13] Permission denied: 'juliodantas2015.json'
tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.
I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt
Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....
I faced same issue this morning when I tried to write data to opened excel file note that you can not edit a file when it's open .
Please close the file and then it work normally

Why can't I open this file for reading in python?

I'm working in Python and I'm confused why I can't open the file I'm trying to. The code is pretty simple. Here it is.
import os
def main():
FILE_NAME = "default_template.csv"
source_path = os.path.join("Documents", FILE_NAME)
file = open(source_path, "r")
At this point I get
IOError: [Errno 2] No such file or directory: 'Documents/FILE_NAME'.
I also decided to try to change directories for whatever reason using os.chdir() and passing just about every high level directory on my computer in seperately and nothing worked. In an attempt to find the fix for opening a file I tried editing the path in a bunch of different ways.
I've tried something like:
os.path.join("/derek/Documents", FILE_NAME)
os.path.join("/Documents", FILE_NAME)
os.path.join("~/derek/Documents", FILE_NAME)
os.path.join("~", FILE_NAME)
If anyone could help me out I would be extremely thankful. I'm still new to using python to navigate and manage files.
Python doesn't expand ~ by default. To make it work try os.path.expanduser:
On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.
source_path = os.path.join("~/Documents", FILE_NAME)
source_path = os.path.expanduser(source_path)

Python can't find file

I am having great difficulty getting python 3.4 to recognize a path or text file on a windows 8 system. I have tried a variety of different approaches but get the similar errors (which likely implies something simple regarding the syntax).
The file itself is located in the same folder as the script file trying to open it:
C:\Users\User\Desktop\Python stuff\Data.txt
for simplicity, the simplest means to access the file (at least that I know of) is
f=open
These lines were coded as:
f = open("Data.txt", "r")
and
f = open("C:/Users/User/Desktop/Python stuff/Data.txt", "r")
but return the error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\Python stuff\Testscript.py", line 3, in <module>
f = open("C:/Users/User/Desktop/Python stuff/Data.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/User/Desktop/Python stuff/Data.txt'
Please check your current directory.
For that just do this:
import os
print (os.getcwd())
I had this same issue. I was using VS Code for my IDE, and had the folder setting to a folder above where I had the file. This obviously was the issue. Once I opened the folder in VScode where the code and the text file were both located I was able to open the file with no issues.
When using Windows you want to keep in mind that if you name the file data.txt the file will actually be data.txt.txt, however Windows will show it as data.txt because windows hides the file extensions by default. This option can be changed by following the steps in the first comment.
If you then search data.txt there really is no such file.
for f = open("Data.txt", "r")
Make sure your .py and .txt files are in the same directory.
for f = open("C:/Users/User/Desktop/Python stuff/Data.txt", "r")
I think the space in Python stuff is messing things up.
Update: I just tried this out .. seems to be fine with the space actually.
>>> [i for i in open('/Users/pk-msrb/projects/temp/temp es/temp.txt')]
['1\n', '2\n', '3\n', '\n']
The problem might be, where exactly you are executing the file.
I had the same problem, but noticed, that the terminal in my IDE (VS Code) is executing the file in a different location. By simply cd to the files location in the terminal, everything went fine. ;)
I had the same problem but now it works for me. I used to open a big map with a lot of sub-maps and the file was in one of the sub-maps. Now I open the submap where my program and file.txt is located and the code open("file.txt", "r") works
I know this is an old question, but here is another option.
set your parent_folder if you have multiple files in the same folder:
parent folder = "C:/Users/User/Desktop/"
extend the folder if necessary:
import os.path
folder = os.path.join( parent_folder, "python stuff" )
add the filename:
file = os.path.join( folder, "Data.txt" )
open the file:
if os.path.exists( file ):
with open( file, "r" ) as infile:
data = infile.read()
or:
import os
import os.path
# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
with open( file, "r" ) as infile:
data = infile.read()
I had a similar issue when using vs code. If you use the built-in green triangle to run, it seems to be able to run the code but it doesn't know where to look for the file. open an integrated terminal to the correct folder and run from the terminal line. Seems like something vs code could figure out...
I had the same problem with pyCharm. I found out that you sometimes have to specify the directory by going to edit config and working directory
Try creating a file using:
f = open("myfile.txt", "x")
Then search your computer for "myfile.txt" which is the file you just created.
Wherever the location of the file is, that is where your code is reading from :)

Categories