FileNotFoundError: [Errno 2] File and path verified? - python-3.x

This is the print out in Python 3.5.1 Shell:
import os
os.getcwd()
'C:\\Users\\victoria\\AppData\\Local\\Programs\\Python\\Python35-32'
>>> import os
>>> os.path.abspath('.\\hello')
'C:\\Users\\victoria\\AppData\\Local\\Programs\\Python\\Python35-32\\hello'
>>> helloFile = open('C:\\Users\\victoria\\AppData\\Local\\Programs\\python\\Python35-32\\hello.txt')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
helloFile = open('C:\\Users\\victoria\\AppData\\Local\\Programs\\python\\Python35-32\\hello.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\victoria\\AppData\\Local\\Programs\\python\\Python35-32\\hello.txt'
What am I reading wrong? I have the .txt file "hello" and it's path verified.

The problem here is that you are trying to open a file that don't exist or you don't put the right name for it. Perhaps you file is actually called hello but when you try to open it you call it as hello.txt which don't exist
Also os.path.abspath don't give you the path to a actual file, it convert a given path into absolute version of it
To check the existence of a file, you must use os.path.exists
example
>>> import os
>>> path=os.path.abspath(".\\fake_file.txt")
>>> path
'C:\\Users\\David\\Documents\\Python Scripts\\fake_file.txt'
>>> os.path.exists(path)
False
>>> path2=os.path.abspath(".\\test.txt")
>>> path2
'C:\\Users\\David\\Documents\\Python Scripts\\test.txt'
>>> os.path.exists(path2)
True
>>>

Related

Error when trying to create a file in a path containing parentheses with Python

Can anyone spot why this is failing?
import pathlib
from shlex import quote
path = 'testdir(abc)/subdir(123)'
filename = 'test'
content = \
"""hello
world
"""
pathlib.Path(path).mkdir(mode=0o770, parents=True, exist_ok=True)
md5_filename = quote(str(pathlib.Path(path) / (filename + '.txt')))
with open(md5_filename, 'w') as f:
f.write(content)
I'm getting this traceback
(tools) $ python test_filemake.py
Traceback (most recent call last):
File "test_filemake.py", line 13, in <module>
with open(md5_filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: "'testdir(abc)/subdir(123)/test.txt'"
I think I don't understand posix paths well enough to understand what's going on. If I take the parentheses out of the directory names in the path, it works fine. shlex.quote() is adding the extra layer of double quotes, which seems to be breaking things.

Error when reading INI file using configparser

Here is my ini file parameters.ini:
[parameters]
Vendor = Cat
Here is my python code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import codecs
import sys
import os
import configparser
### Script with INI file:
INI_fileName="parameters.ini"
if not os.path.exists(INI_fileName):
print("file does not exist")
quit()
print("Here is the INI_fileName: " + INI_fileName)
config = configparser.ConfigParser()
config.read('INI_fileName')
vendor = config['parameters']['Vendor']
print("Here is the vendor name: " + vendor)
Here is the error:
python3 configParser-test.py
Here is the INI_fileName: parameters.ini
Traceback (most recent call last):
File "configParser-test.py", line 18, in <module>
vendor = config['parameters']['Vendor']
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/configparser.py", line 958, in __getitem__
raise KeyError(key)
KeyError: 'parameters'
If I run the same code interactively it works. However if it was related to the file path, the error would be different, I assume: "file does not exist". Interactively:
>>> print(INI_fileName)
parameters.ini
>>> config.read('INI_fileName')
[]
>>> config.read('parameters.ini')
['parameters.ini']
>>>
Why is it not picking up the file name?
While playing with the interactive command I think I found the reason. Since I use the filename as variable i do not need to use quotes! Omg...
config.read(INI_fileName)
This problem may be due to the UTF byte order mark (BOM) added by Windows text editor.
BOM should be deleted before reading the config parameters in Linux/Unix.
Try:
config = configparser.ConfigParser()
config_file_path = '/app/config.ini' # full absolute path here!
s = open(config_file_path, mode='r', encoding='utf-8-sig').read()
open(config_file_path, mode='w', encoding='utf-8').write(s)
config.read(config_file_path)
# now check if it is OK

FileNotFoundError: [Errno 2] No such file or directory: '2MCREF~E.JPG'

I'm trying to open an image that resides at a different location than my script
Code:
import os
from PIL import Image
folder = '/Users/abc'
if not os.listdir(folder):
print('Folder not found')
else:
print('"{}" found'.format(folder))
for file in os.listdir(folder):
print(file)
data = Image.open(file,'r')
print('Done')
Error:
"/Users/abc" found
2MCREF~E.JPG
Traceback (most recent call last):
File "img_to_s3bucket.py", line 25, in <module>
data = Image.open(file,'r')
File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/PIL/Image.py", line 2770, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '2MCREF~E.JPG'
How to tackle this?
This could be because your working directory and the location of the file are not same.
You could do this by specifying the full file path in the below command:
data = Image.open(file,'r')
you can do this by:
data = Image.open(os.path.join(folder, file),'r'))

Os walk directory return string literal for unzipping

The problem occurs where the string variable tries to get read by zipfile.Zipfile(variable). The callback is file does not exist. This is because it is adding an extra \ to each folder. I tried several things to try and make the string into a literal but when I do this it prints an extra \\\. I tried even making that a literal but as I would expect it repeated the same thing returning \\\\\.Any insight would be greatly appreciated!!!
The code structure is below and here are the callback functions
Traceback (most recent call last):
File "C:\Users\Yume\Desktop\Walk a Dir Unzip and copy to.py", line 17, in <module>
z = zipfile.ZipFile(zf, 'r')
File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: "C:\\Users\\Yume\\AppData\\Roaming\\
Traceback (most recent call last):
File "C:\Users\Yume\Desktop\Walk a Dir Unzip and copy to.py", line 17, in <module> z = zipfile.ZipFile(rzf, 'r')
File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
self.fp = io.open(file, filemode)
OSError: [Errno 22] Invalid argument: '"C:\\\\Users\\\\Yume\\\\AppData\\\\Roaming\\\\
z = zipfile.ZipFile(rrzf, 'r')
File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
self.fp = io.open(file, filemode)
OSError: [Errno 22] Invalid argument: '\'"C:\\\\\\\\Users\\\\\\\\Yume\\\\\\\\AppData\\\\\\\\Roaming\\\\\\\
CODE:
import os
import re
from shutil import copyfile
import zipfile
import rarfile
isRar = re.compile('.+\\.rar')
isZip = re.compile('.+\\.zip')
for folderName, subfolders, filenames in os.walk(r'C:\Users\Yume\AppData'):
if isZip.match(str(filenames)):
zf = folderName+ str(subfolders)+str(filenames)
rzf = '%r'%zf
z = zipfile.ZipFile(zf)
z.extractall(r'C:\Users\Yume')
z.close()
if isRar.match(str(filenames)):
rf = folderName+ str(subfolders)+str(filenames)
rrf = "%r"%rf
r = rarfile.RarFile(rf)
r.extractall(r'C:\Users\Yume')
r.close()
My problem was corrected by running a for loop through the file list created by os walk. I cleaned up my code and here is a working program that walks a directory find a compressed .zip or .rar and extracts it to the specified destination.
import os
import zipfile
import rarfile
import unrar
isRar = re.compile('.*\\.rar')
isZip = re.compile('.*\\.zip')
for dirpath, dirnames, filenames in os.walk(r'C:\Users\'):
for file in filenames:
if isZip.match(file):
zf = os.path.join(dirpath, file)
z= zipfile.ZipFile(zf)
z.extractall(r'C:\Users\Unzipped')
z.close()
if isRar.match(file):
rf = os.path.join(dirpath, file)
r = rarfile.RarFile(rf)
r.extractall(r'C:\Users\Unzipped')
r.close()

Python3: ZipFile instance has no attribute 'extractall'

from zipfile import ZipFile
fzip=ZipFile("crackme.zip")
fzip.extractall(pwd=b"mysecretpassword")
the script works only on IDLE, but when i run it from the command line, it displays:
unzip.py
fzip.extractall(pwd=b"mysecretpassword")
^
SyntaxError: invalid syntax
what's wrong?
It works (Ubuntu 13.04):
>>> import sys
>>> sys.version
'3.3.1 (default, Apr 17 2013, 22:32:14) \n[GCC 4.7.3]'
>>> from zipfile import ZipFile
>>> f = ZipFile('a.zip')
BTW, pwd should be bytes objects:
>>> f.extractall(pwd="mysecretpassword")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.3/zipfile.py", line 1225, in extractall
self.extract(zipinfo, path, pwd)
File "/usr/lib/python3.3/zipfile.py", line 1213, in extract
return self._extract_member(member, path, pwd)
File "/usr/lib/python3.3/zipfile.py", line 1275, in _extract_member
with self.open(member, pwd=pwd) as source, \
File "/usr/lib/python3.3/zipfile.py", line 1114, in open
raise TypeError("pwd: expected bytes, got %s" % type(pwd))
TypeError: pwd: expected bytes, got <class 'str'>
>>> f.extractall(pwd=b'mysecretpassword')
>>>
According to zipfile.ZipFile.extractall documentation:
Warning Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of
path, e.g. members that have absolute filenames starting with "/" or
filenames with two dots "..".
Changed in version 3.3.1: The zipfile module attempts to prevent that. See extract() note.

Resources