Python Forum
How to concatenate filepath with variable? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to concatenate filepath with variable? (/thread-36238.html)



How to concatenate filepath with variable? - Mark17 - Jan-31-2022

Hi all,

I'm trying to write a program that will replace a couple lines of a new program (placed in a set filepath) and replace a couple filepath lines to reflect my computer rather than the one who wrote it.

He uses spaces in his filename, which seems to causes issues for me so I'm stripping out the spaces.

I'm having particular trouble with Line 18, though:

#This program will take John's new code files from Input folder and save code with my filepath in Output folder

import glob, os, shutil

feed_dir = r"C:\Users\Mark\Desktop\john_filepath_conversion\Input"

os.chdir(feed_dir)

for file in glob.glob("*.*"):
    barfile = open(file, "r")   #file is the string containing each filename returned by the glob function
    print(f'Orig name is {barfile.name}.')
    new_name = barfile.name.replace(' ','')
    print(f'New name is {new_name}.')
    barfile.close()

#os.rename(barfile.name,new_name)

shutil.move(barfile.name,r"C:\Users\Mark\Desktop\john_filepath_conversion\Converted\"+new_name")
#is there a way to incorporate the value of new_name into the filepath?
Thanks for any help!


RE: How to concatenate filepath with variable? - Larz60+ - Jan-31-2022

Can't do this: shutil.move(barfile.name,r"C:\Users\Mark\Desktop\john_filepath_conversion\Converted\"+new_name")

instead use something like:
newfilename = f"C:\Users\Mark\Desktop\john_filepath_conversion\Converted\{new_name}"
shutil.move(barfile.name,newfilename)
Edit: Jan31 - 10:21 EST missing letter fixed


RE: How to concatenate filepath with variable? - Mark17 - Jan-31-2022

(Jan-31-2022, 06:04 PM)Larz60+ Wrote: Can't do this: shutil.move(barfile.name,r"C:\Users\Mark\Desktop\john_filepath_conversion\Converted\"+new_name")

instead use something like:
ewfilename = f"C:\Users\Mark\Desktop\john_filepath_conversion\Converted\{new_name}"
shutil.move(barfile.name,newfilename)

Very nice!