Python File Check and Creation - python-3.x

I am trying to check or create a directory and I am getting this error:
/usr/bin/python3.6 /home/user/Development/americas.py Traceback (most
recent call last): File "/home/dquezada/Development/americas.py",
line 23, in
os.mkdir(path) FileNotFoundError: [Errno 2] No such file or directory: '/home/dquezada/Development/data/maps/americas/'
Process finished with exit code 1
Below is my code:
path = '/home/user/Development/data/maps/americas/'
# Check if path exists, if it does not it creates it
if not os.path.exists(path):
os.mkdir(path)
wm.render_to_file(path + timeStamp + '_americas.svg')

I believe os.path.isdir(path) is what you are looking for.
This will return True if it is a directory, or False if it isn't.
os.path.exists(path) is not intended for what you are using it for.
path = '/home/user/Development/data/maps/americas/'
# Check if path exists, if it does not it creates it
if not os.path.isdir(path):
os.mkdir(path)
wm.render_to_file(path + timeStamp + '_americas.svg')
That should work for you.

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.

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'))

How to convert users input to file path in Python

I am currently trying to get the file_path (suppose ~/hello_world/) as user input and list all the files inside this directory. I can do this exact same thing if I pass ~/hello_world as sys.argv however, I can't seem to get it work if I take it as an input. I am trying to work the code from any directory and user inputted file path will be from /home/ubunut/...
Here's my working code as sys.argv:
This code is intended for unix based os only for now.
if len(sys.argv) == 2:
path = sys.argv[1]
files = os.listdir(path)
for name in files:
print(name)
Here's the code I am trying to work with:
path = input("file_path: ")
files = os.listdir(path)
for name in files:
print(name)
This is when it crashed with the following error:
Traceback (most recent call last):
File "test.py", line 14, in <module>
files = os.listdir(path)
FileNotFoundError: [Errno 2] No such file or directory: '~/hello_world/'
Thanks in advance.
You need to expand the ~ like in the answer to this question
The following worked for me
import os
path = input("enter filepath: ")
for f in os.listdir(os.path.expanduser(path)):
print(f)

Error when Unzipping with Pyside Qtgui

When I run my program, I get the following error and am not sure on how to correct it. Can someone help with explaining what this error is and how to correct it? Newb here so details are appreciated. Thanks for your time in advance!
Code:
#!/usr/bin/python
import zipfile
from PySide import QtGui
import re
#Select file to extract
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.AnyFile)
if (dialog.exec()):
fileName = dialog.selectedFiles()
#Select Directory to extract to
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
if (dialog.exec()):
dirName = dialog.selectedFiles()
print("Extracting.....")
zFile= zipfile.ZipFile(fileName)
zFile.extractall(dirName)
Error output:
Traceback (most recent call last):
File "C:\Users\Jennifer\Documents\BatchScripts\unzip.py", line 22, in <module>
zFile= zipfile.ZipFile(fileName)
File "C:\Python33\lib\zipfile.py", line 933, in __init__
self._RealGetContents()
File "C:\Python33\lib\zipfile.py", line 970, in _RealGetContents
endrec = _EndRecData(fp)
File "C:\Python33\lib\zipfile.py", line 237, in _EndRecData
fpin.seek(0, 2)
AttributeError: 'list' object has no attribute 'seek'
In your file and target directory code blocks, dialog.selectedFiles() returns a list. zipfile.ZipFile can only handle one file at a time, hence your error. To iterate over the list being provided by dialog.selectedFiles(), use the following:
for archive in fileName: # you should probably change it to fileNames to reflect its true nature
zfile = zipfile.ZipFile(archive)
print("Extracting " + str(zfile.filename) + "...")
zfile.extractall(dirName[0]) # also a list, extract to first item and ignore rest
and you should be all set.

python : how to use wave module?

when I try the following program :
import wave
w = wave.open('f.wav', 'r')
for i in range():
frame = w.readframes(i)
the following error comes :
Traceback (most recent call last):
File "F:/Python31/fg.py", line 2, in <module>
w = wave.open('f.wav', 'r')
File "F:\Python31\lib\wave.py", line 498, in open
return Wave_read(f)
File "F:\Python31\lib\wave.py", line 159, in __init__
f = builtins.open(f, 'rb')
IOError: [Errno 2] No such file or directory: 'f.wav'
can u tell me wat could b the reason ???
The file is not in the path you put that Python interpreter can find. Check that f.wav is in the same path of your script (or chance the path in open).
Is not a wave issue at all.
You are running the python script from a directory where no file f.wav exists. It can't find the file to read. Either copy f.wav to that directory or run you script from the directory f.wav is located in.

Resources