Python Forum
Changing Directory based on user input
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Changing Directory based on user input
#1
Hi there,

I'm trying to create a program whereby a user can resize images in their own, inputted directory. As you can see below, I am able to view their directory, but am unable to change the working directory of the program. What keeps happening is that the program creates a folder called 'path' in my own working directory, which is not what I want it to do.

 from PIL import Image
import os
import glob

while True:
    dirname = input("Please enter/copy and paste the folder location of your images here > ")
    path = os.path.join(dirname,"**")
    oldpath = os.getcwd()
    print(oldpath)
    newpath = os.chdir('path')
    print(os.getcwd())
I also need to ensure that, as users would be resizing images in bulk, that it doesn't come up with an error after creating the new sub-directory. In other words, to make sure that it doesn't try to create a sub-directory twice.

This is the code in full so far:

from PIL import Image
import os
import glob

while True:
    dirname = input("Please enter/copy and paste the folder location of your images here > ")
    path = os.path.join(dirname,"**")
    oldpath = os.getcwd()
    print(oldpath)
    newpath = os.chdir('path')
    print(os.getcwd())
   
    
    #newdir = os.makedirs('path/Thumbnails')

    math = input("What type of file are you working with? Please answer with file extension type - e.g. .jpg ")
    if math == ".jpg":
        for x in glob.glob(path, recursive=True):
            if x.endswith(".jpg"):
                print (path, x)
             
                xm = Image.open(x)
                new_height = int(input("Height of thumbnail in pixels?"))
                new_width = int(input("Width of thumbnail in pixels?"))

                new_size = xm.resize((new_width, new_height))
                new_size.show()
                
                hapus = input("Are you happy with this image - yes or no? ")
                if hapus == "yes":
                    print (path)
                    
    
    
    if math == ".png":            
        for y in glob.glob(path, recursive=True):
            if y.endswith(".png"):
                print (path, y)
                os.startfile(y)
                ym = Image.open(y)
                new_height = int(input("Height of thumbnail in pixels?"))
                new_width = int(input("Width of thumbnail in pixels?"))

                new_size = ym.resize((new_width, new_height))
                new_size.show()
                
                
                
                
                #break
                
       







#if hapus == "yes":
As I say, I have come across a bit of a stumbling block with it and need to know what I've done wrong. If anyone can help, I would be very grateful.

Many thanks,
paulmerton4pope
Reply
#2
In line 10, you are passing the string 'path' to os.chdir(). Don't you mean to pass the variable instead?
Reply
#3
(Aug-12-2020, 09:41 PM)GOTO10 Wrote: In line 10, you are passing the string 'path' to os.chdir(). Don't you mean to pass the variable instead?

Quite possibly - I am very new to this, so am probably making some big errors.

Basically my aim is to change the working directory to the file that the user inputs from line six, so that when they save the images, they are able to create a sub-directory in their own folder.

Many thanks,
paulmerton4pope
Reply
#4
In line 10 get rid of the quotes around path
Reply
#5
I don't have a ton of experience with the os module myself, but os.chdir('path') attempts to change the directory to 'path', whereas os.chdir(path) attempts to change the directory to match the string you assigned to the path variable on line 7. I'm not sure what OS you are using, but in Windows 10 this still fails because of the "**" joined to the path entered by the user.

This code changes the working directory successfully:
import os

print('Current directory:', os.getcwd())
path = 'C:\TMP'
os.chdir(path) # path must be valid on the OS for this to succeed
print('Current directory after change:', os.getcwd())
Output:
Current directory: C:\\Program Files (x86)\\Python38-32 Current directory after change: C:\\TMP
Reply
#6
(Aug-12-2020, 10:03 PM)GOTO10 Wrote: I don't have a ton of experience with the os module myself, but os.chdir('path') attempts to change the directory to 'path', whereas os.chdir(path) attempts to change the directory to match the string you assigned to the path variable on line 7. I'm not sure what OS you are using, but in Windows 10 this still fails because of the "**" joined to the path entered by the user.

This code changes the working directory successfully:
import os

print('Current directory:', os.getcwd())
path = 'C:\TMP'
os.chdir(path) # path must be valid on the OS for this to succeed
print('Current directory after change:', os.getcwd())
Output:
Current directory: C:\\Program Files (x86)\\Python38-32 Current directory after change: C:\\TMP

Thank you for that, that solves that problem.

But I am now finding that the code from line 16 (in my original post) is now not running at all - is there something that I need to add to it to make it work?

Many thanks,
paulmerton4pope
Reply
#7
It doesn't even print the input statement? What do you mean not running at all?
Reply
#8
(Aug-13-2020, 02:06 AM)jefsummers Wrote: It doesn't even print the input statement? What do you mean not running at all?

It does print the input statement, but then goes straight back to the previous input (of entering the directory) as opposed to processing the file type.

Many thanks,
paulmerton4pope
Reply
#9
I haven't used glob. Try print(x) just after your for statement in line 18 to see if it is giving you the string you think you are getting. Reading the docs on glob.glob and playing with it, my suspicion is that you are not setting up your path properly. With a hard coded path I am getting it to follow the logic.
Reply
#10
When you pass the path variable to os.chdir(), you need it to be a valid directory like 'C:\TMP'. When you pass the path variable to glob.glob() (lines 18 and 36), you need it to include a wildcard like 'C:\TMP\*'. My guess is you are passing path without a wildcard in lines 18 and 36, so your glob.glob() loop is not actually finding anything that satisfies the if condition (nothing that ends with .jpg or .png).

import glob

print('Printing items using C:\TMP as path')
for item in glob.glob('C:\TMP'):
    print(item)
    
print('Printing items using C:\TMP\* as path')
for item in glob.glob('C:\TMP\*'):
    print(item)
Output:
Printing items using C:\TMP as path C:\TMP Printing items using C:\TMP\* as path C:\TMP\Testing.jpg C:\TMP\Placeholder.jpg
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a menu and execute a function based on user selection in python? Thedarkphoenix 1 1,317 Nov-23-2022, 07:53 PM
Last Post: Larz60+
Question Simulate an answer based on user input [Beginner needs guidance] Bombardini 1 1,281 Nov-12-2022, 03:47 AM
Last Post: deanhystad
  Print user input into triangle djtjhokie 1 2,369 Nov-07-2020, 07:01 PM
Last Post: buran
  sys.stdin to do a word count based on user entry Kaltex 3 3,672 Jul-19-2020, 01:54 PM
Last Post: deanhystad
  how to add the user input from file into list wilson20 8 4,312 May-03-2020, 10:52 PM
Last Post: Larz60+
  Writing a function that changes its answer based on user input SirRavenclaw 2 2,801 Dec-21-2019, 09:46 PM
Last Post: Clunk_Head
  Print the longest str from user input edwdas 5 4,138 Nov-04-2019, 02:02 PM
Last Post: perfringo
  how to add user input to a dictionary to a graph KINGLEBRON 3 3,025 Jul-31-2019, 09:09 PM
Last Post: SheeppOSU
  New to Python - tiny coding assistance on user input function and assign to variable Mountain_Duck 1 2,497 Mar-23-2019, 06:54 PM
Last Post: Yoriz
  Extracting list element with user input valve 1 2,565 Mar-11-2019, 07:37 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020