I am creating a decision tree using a dataset named as "wine": i am trying following code to execute:
dt = c.fit(X_train, y_train)
Creating the image of the decision tree:
def show_tree(tree, features, path):
f = io.StringIO()
export_graphviz(tree, out_file=f, feature_names=features)
pydotplus.graph_from_dot_data(f.getvalue()).write_png(path)
img = misc.imread(path)
plt.rcParams["figure.figuresize"] = (20 , 20)
plt.imshow(img)
Calling the image:
show_tree(dt, features, 'dec_tree_01.png')
but when i call the image it gives the following error:
GraphViz's executables not found
I have installed graphviz-2.38msi from there website...but the same error is continuously showing.
I have also added environment variables string in the user variable like this:
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Graphviz2.38\bin;
But it could also not solve the problem.
try appending the path to os variable in code like
import os
os.environ["PATH"] += os.pathsep + 'C:\Program Files (x86)\Graphviz2.38\bin'
Note: Do it at top of he code before excution of show_tree()
Related
I was making a project that has you type what's on the screen, and I was trying to get it to generate random words from a file. but I got an error saying FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'. I double-checked that the file was in the same directory and it was named right. Then I went back to my other program using this file, and it didn't work either (Even though it worked perfectly before). I tried using a shorter file to see if that was the problem, but it still gave me the same error.
Here is my (incomplete) code:
from Tkinter import Tk, Entry
import random
words = open('words.txt')
tab = Tk()
words = words.readlines()
totype = words[random.randint(1, len(words))]
print(totype)
How can I fix this?
Check that the directory you're running python from is the correct directory.
On python 3.4+, you can use the pathlib module to open files in the same directory as the script easily:
from pathlib import Path
p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
words = f.read()
You can check this with:
import os
cwd = os.getcwd()
And use the relative directory from that.
Alternatively, use the full directory.
You can get the full path of the script using:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
Then you can use dir_path + file_name to get your full file path.
You have to give directory path specifying where the file is located if the file is located in same directory as your script file you can do
from Tkinter import Tk, Entry
import random
words = open('./words.txt')
tab = Tk()
words = words.readlines()
totype = words[random.randint(1, len(words))]
print(totype)
if it is located in some other folder then you can do
file = open(r'C:\Users\Directory\sample.txt') #example
words = open(file)
tab = Tk()
words = words.readlines()
totype = words[random.randint(1, len(words))]
print(totype)
# load all images for the players
animation_types = ['Idle', 'Run', 'Jump']
for animation in animation_types:
# reset temporary list of images
temp_list = []
# count number of files in the folder
num_of_frames = len(os.listdir(f'Assets/{self.char_type}/{animation}'))
for i in range(num_of_frames):
img = pygame.image.load(f'Assets/{self.char_type}/{animation}/{i}.png')
img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale)))
temp_list.append(img)
self.animation_list.append(temp_list)
I am fairly new to python and pygame and am making my first game. I ran into a problem where i'm trying to access files for an animation. For the idle animation the directory is Assets/player/Idle. Inside the folder are 5 images. When I run the code I receive this error:
img = pygame.image.load(f'Assets/{self.char_type}/{animation}/{i}.png')
FileNotFoundError: No such file or directory
I am pretty sure the problem is with the images in the animation folder as I made sure the other folders were found and they were fine. I honestly don't know what to do. If you need the full script then I can send it. Thank you.
I am on a linux system and I had a similar problem. This is what worked for me:
import os
PATH = os.path.dirname(os.path.abspath(__file__))
def get_path(*slices):
return os.path.join(PATH, *slices)
First get the path to the containing directory then in the function return the joined path.
In your case you then need to call:
num_of_frames = len(os.listdir(get_path('Assets', self.char_type, animation))
and
img = pygame.image.load(get_paht('Assets', self.char_type, animation, str(i) + '.png')
other sources of the error:
you are on a windows machine (the path-splitting character on windows is not /)
the files aren't named correctly (0.png, 1.png, 2.png, 3.png, 4.png)
EDIT: Debugging idea: add
print('loading path =', f'Assets/{self.char_type}/{animation}/{i}.png')
before loading the image and check if this file actually exists.
I'm working on a program to open a folder full of images, copy the images, and then save the copies of the images in a different directory.
I am using Python 2.4.4, but I am open to upgrading the program to a newer version if that allows me to import PIL or Image because I cannot do that with my version.
As of now, I have:
import Image
import os
def attempt():
path1 = "5-1-15 upload"
path2 = "test"
listing = os.listdir(path1)
for image in listing:
im = Image.open(path1)
im.save(os.path.join(path2))
I am new to Python, so this is probably obviously wrong for numerous reasons.
I mostly need help with opening a folder of images and iterating through the pictures in order to save them somewhere else.
Thanks!
Edit- I've tried this now:
import shutil
def change():
shutil.copy2("5-1-15 upload", "test")
And I am receiving an IOError now: IOError: System.IO.IOException: Access to the path '5-1-15 upload' is denied. ---> System.UnauthorizedAccessException: Access to the path '5-1-15 upload' is denied.
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in :0
Am I entering the folders wrong? How should I do this if it an a folder within a specific computer network.
Basically there is a folder called images with multiple subfolders within it which I am trying to extract the images from.
Based on this answer, copyfile will do the trick, as you are just copying images from one side to another, as if it was another type of file.
import shutil
import os
def attempt():
path1 = "5-1-15 upload"
path2 = "test"
listing = os.listdir(path1)
for image in listing:
copyfile(image, path2)
This'd be my first post here, and I'm having serious issues about file reading with Python GUI.
So, I'm totally lost in trying to figure a smarter way to write a code in Python 2.7 using GUI to browse a directory and read ALL files in it for further operations. In my case, the files I'm reading are images and I'm trying to save it in an array.
I'm using those numpy, scikits etc, for easing my image-processing work. I am trying to process 3 images named "pulse1.jpg" to "pulse3.jpg".
Here's my work below. My apologies if it's kinda bit messy/unclear, especially since I can't post images yet:
import os
import numpy as np
import cv2
from matplotlib import pyplot as plt
from skimage import color, data, restoration
# first we specify the file directory
directory = 'I:\\My Pictures\\toby arm pics'
filename = "pulse"
# initiate file reading
isfile = os.path.isfile
join = os.path.join
# first, we get the number of files (images)
# in the directory
number_of_files = sum(1 for item in os.listdir(directory)\
if isfile(join(directory, item)))
X = [] # we'll store the read images here
i = 1 # initiate iteration for file reading
string = "" # initiation
# read the images from directory
# and save it to array X
while i <= number_of_files:
string = directory + "\\" + filename + str(i) + ".jpg"
temp = cv2.imread(string, -1)
X.append(temp)
i += 1
Thank you so much for your help, guys!
>>> import Tkinter, tkFileDialog
>>> root = Tkinter.Tk()
>>> root.withdraw()
''
>>> dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Pick a directory')
>>> for filename in os.listdir(dirname):
>>> temp = cv2.imread(filename,-1)
maybe?
(I snagged most of this code from http://code.activestate.com/recipes/438123-file-tkinter-dialogs/)
I try to access to one of my pictures in one of my directories but i get an error each time.
Actually, my folder is like that :
gamefolder:
lib:
main.py
level.py
othermodules.py
...
data:
Level1.png
otherspictures.png
In the primary python file who is main.py, i wrote :
currentpath = os.path.dirname(sys.argv[0])
parentpath = os.path.dirname(currentpath)
sys.path.append(os.path.join(parentpath, 'data'))
But I always get an error in one of my script : level.py called by main.py :
pygame.error: Couldn't open Level_1.png
The code in level.py is like that :
self.image = pygame.image.load('Level1.png').convert_alpha()
I'm not yet familiar with python path .. But it would be so nice if i can arrange that folder like that, which is very elegant !
Thanks to help :)
Try
currentpath = os.path.dirname(os.path.realpath(__file__))
# or
#currentpath = os.path.dirname(os.path.realpath(sys.argv[0]))
datadir = os.path.join(os.path.dirname(currentpath), 'data')
self.image = pygame.image.load(os.path.join(datadir, 'Level1.png')).convert_alpha()
The path sys.argv[0] can be main.py and its dirname is an empty string
Updated
As the manual of pygame
You should use os.path.join() for compatibility.