0

My code

import os.path #gets the module
beginning = input("Enter the file name/path you would like to upperify: ")
inFile = open(beginning, "r") 
contents = inFile.read()
moddedContents = contents.upper() #makes the contents of the file all caps
head,tail = os.path.split(beginning) #supposed to split the path
new_new_name = "UPPER" + tail #adds UPPER to the file name
final_name = os.path.join(head + new_new_name) #rejoins the path and new file name
outFile = open(final_name, "w") #creates new file with new capitalized text 
outFile.write(moddedContents)
outFile.close()

I'm just trying to change the file name to add UPPER to the beginning to the file name via os.path.split(). Am I doing something wrong?

asked May 20, 2014 at 17:00
3
  • 1
    What's the point of calling os.path.join the way you do? Commented May 20, 2014 at 17:01
  • Of course I don't know if you are doing something wrong- you haven't even said what isn't working! Commented May 20, 2014 at 17:02
  • possible duplicate of How do I change the name of a file path correctly in Python? Commented May 21, 2014 at 22:30

2 Answers 2

2

Change

final_name = os.path.join(head + new_new_name)

to

final_name = head + os.sep + new_new_name
answered May 20, 2014 at 17:09
Sign up to request clarification or add additional context in comments.

Comments

1

head from os.path.split doesn't have a trailing slash in the end. When you join the head and new_new_name by concatenating them

head + new_new_name 

you don't add that missing slash, so the whole path becomes invalid:

>>> head, tail = os.path.split('/etc/shadow')
>>> head
'/etc'
>>> tail
'shadow'
>>> head + tail
'/etcshadow'

The solution is to use os.path.join properly:

final_name = os.path.join(head, new_new_name)
answered May 20, 2014 at 17:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.