How to open a random Image from a given file directory? - python

I am trying to open the image from this directory but am not been able to.
It gives me the following error:
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect.
This is my code:
import os, random
random.choice(os.listdir("C:\\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"+'png'))
In here , in the folder backgrounds there are many images.I want a random Image to open.But while running the program , I am getting WindowsError.
What am I doing wrong?
Edit 1
I tried this:
random.choice(os.listdir(r"C:\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"+'png'))
But am getting the error:
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect:
'C:\Users\rkp10\AppData\Local\Google\Chrome\User
Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds\*.png/.'
Edit 2
I tried this:
import os, random
a=random.choice(os.listdir(r"C:\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"))
os.open(a)
Now I dont get error but it does not open the image either.
Edit 3
I have also tried:
import random,os
folder= "C:\\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"
a=random.choice(os.listdir(folder))
print(a)
from PIL import Image
file = folder+'\\'+a
Image.open(file).show()
#os.open(a, os.O_RDWR)
from PIL import Image
file = folder+'\\'+a
Image.open(file).show()
But got the following error once again:
Traceback (most recent call last): File "G:\Grade 12
Project\auto.py", line 4, in
a=random.choice(os.listdir(folder)) WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:
'C:\Users\rkp10\AppData\Local\Google\Chrome\User
Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca'
Here(the yellow highlighted part) is the directory where my images are stored.

Use the PIL instead.
import os, random
folder=r"D:\Study\SO"
a=random.choice(os.listdir(folder))
print(a)
#os.open(a, os.O_RDWR)
from PIL import Image
file = folder+'\\'+a
Image.open(file).show()
source:
Open and display .png file in python using PIL
The problem with this is that a doesn't have absolute path to that chosen random files.
In Edit 1, the "png" gets concatenated but there is no folder named "backgroundspng"
In Edit 2, you haven't given the flags for os.open() which can be found here.
In Edit 3, please make sure that you are using the r before string.
In you case, use this :
folder = r"C:\\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"

You need to use a raw string by prepending the string with r:
random.choice(os.listdir(r"C:\Users\rkp10\AppData\Local\Google\Chrome\User Data\Default\Extensions\laookkfknpbbblfpciffpaejjkokdgca\0.91.6_0\backgrounds"+'png'))
Else, you would need to escape each backslash by another backslash.

Related

How to solve the Error of pdf2jpg module?

I want to convert pdf to images.
I am using pdf2jpg Module for this.
But It is giving me Following Error:
[WinError 2] The system cannot find the file specified
The path Which I am giving, is correct.
This is my code:
import os
from pdf2jpg import pdf2jpg
find=os.getcwd()
i_p=r"find/k.pdf"
o_p=r"find/data"
result = pdf2jpg.convert_pdf2jpg(i_p, o_p, pages="ALL")
You are setting the input and output paths incorrectly. Assuming your input PDF is in the same directory as your script, following code should work:
i_p = os.path.join(find, "k.pdf")
o_p = os.path.join(find, "data")

Load a gpx file on python

I'm a Mac user. I'm trying to load a .gpx file on python,using the following code:
import gpxpy
import gpxpy.gpx
gpx_file = open('Downloads/UAQjXL9WRKY.gpx', 'r')
And I get the following message:
FileNotFoundError: [Errno 2] No such file or directory: 'Downloads/UAQjXL9WRKY.gpx'
Could someone help me figure out why? Thanks in advance.
Obviously, one reason would be that the file does not, in fact, exist, but let us assume that it does.
A relative filename (i.e, one that does not start with a /) is interpreted relative to the current working direcory of the process. You are apparently expecting that to be the user's home directory, and you are apparently wrong.
One way around this would be to explicitly add the user's home directory to the filename:
import os
home = os.path.expanduser('~')
absfn = os.path.join(home, 'Downloads/whatever.gpx')
gpx_file = open(absfn, ...)

how to check if a file exists and create one if it's missing, while the path to the file is incomplete as below

I have to create a empty text file called file.txt under this path
/home/project/test*/today/file.txt
test* changes each time like test_product or test_1 etc..
I tried the following code:
if(os.path.exists("/home/project/test*/today/file.txt"):
print "Found"
else:
open("/home/project/test*/today/file.txt",a).close()```
I got this error
```IOError: [Errno 2] No such file or directory: '/home/project/test*/today/file.txt'```
I understand I can use glob to search the files with paths like * , but I am unable to figure out how to create a file while having * in the path.
Your code logically doesn't make any sense. What you're basically saying is
if the file exists: display the text Found
otherwise the file does not exist, so try to open the file that does not exist
I'll tell you why it doesn't work. os module does not support wildcards.
If you wanted to use wildcards * you could use glob.
import glob
import os
from pathlib import Path
def check_for_files(filepath):
for filepath_object in glob.glob(filepath):
if os.path.isfile(filepath_object):
return True
return False
file_to_check = "/home/project/test*/today/file.txt"
if not (check_for_files(file_to_check):
Path(file_to_check).touch()

Pillow : File not found

I would like to use images with tkinter's canvas but I can't open image with Pillow. In fact, I have all my images in the same folder as my code but when I put "icon.png" it doesn't work. Then when I put the full path to the image (C:/Users/myName/Desktop/PythonWork/game/src/icon.png) , it works.
File "F:\Python\lib\site-packages\PIL\Image.py", line 2312, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'icon.png'
Therefore my question is : How do I make the relative path to work ?
Thanks in advance for your help :)
If you want to reference files in the same directory as in Image.py, put this in Image.py:
import os
# get the directory path of the current python file
my_path = os.path.dirname(__file__)
You can then append to that path the name of the file you want to access.

Python - IO:Error Cannot Identify Image File

I'm working on an image to text OCR system and I kept receiving an error on the console stating
Traceback (most recent call last):
File "crack_test.py", line 48, in <module>
temp.append(buildvector(Image.open("./iconset/%s/%s"%(letter,img))))
File "/Users/seng_kin/anaconda/lib/python2.7/site-packages/PIL/Image.py", line 2290, in open
% (filename if filename else fp))
IOError: cannot identify image file './characterset/a/.DS_Store'
I have a folder in a ../OCR/characterset/ directory which has 26 subfolders representing 26 characters whereby each subfolder contains a .PNG of a character.
The score_test.py is stored in ../OCR/
score_test.py Code:
from PIL import Image
import os, sys
import math
****def functions****
iconset = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z']
imageset = []
for letter in iconset:
for img in os.listdir('./characterset/%s/'%(letter)):
temp = []
if img != "Thumbs.db": #windows check...
temp.append(buildvector(Image.open("./characterset/%s/%s"%(letter, img))))
imageset.append({letter:temp})
I saw other solutions on the website but all is related to the absence of from PIL import Image. Am I missing something?
.DS_Store is a "hidden" file in directories on Mac OS X.
In your if img != "Thumbs.db" check, you should add:
if not img.startswith('.') and img != 'Thumbs.db':
this way you filter out all "hidden" files.

Categories

Resources