0

My code

specFileName = input("Enter the file path of the program you would like to capslock: ")



inFile = open(specFileName, 'r')
ified = inFile.read().upper()

outFile = open(specFileName + "UPPER", 'w')
outFile.write(ified)
outFile.close()


print(inFile.read())

This is basically make to take in any file, capitalize everything, and put it into a new file called UPPER"filename". How do I add the "UPPER" bit into the variable without it being at the very end or very beginning? As it won't work like that due to the rest of the file path in the beginning and the file extension at the end. For example, C:/users/me/directory/file.txt would become C:/users/me/directory/UPPERfile.txt

3
  • where do you want put it? Commented May 19, 2014 at 23:39
  • @Padraic Cunningham At the beginning of the filename instead of the beginning of the file path. For example C:/users/me/directory/file.txt would become C:/users/me/directory/UPPERfile.txt Commented May 19, 2014 at 23:41
  • possible duplicate of How do I modify a filepath using the os.path module? Commented May 21, 2014 at 22:30

2 Answers 2

1

Look into the methods os.path.split and os.path.splitext from the os.path module.

Also, quick reminder: don't forget to close your "infile".

Sign up to request clarification or add additional context in comments.

Comments

0

Depending on exactly how you're trying to do this, there's several approaches.

First of all you probably want to grab just the filename, not the whole path. Do this with os.path.split.

>>> pathname = r"C:\windows\system32\test.txt"
>>> os.path.split(pathname)
('C:\\windows\\system32', 'test.txt')

Then you can also look at os.path.splitext

>>> filename = "test.old.txt"
>>> os.path.splitext(filename)
('test.old', '.txt')

And finally string formatting would be good

>>> test_string = "Hello, {}"
>>> test_string.format("world") + ".txt"
"Hello, world.txt"

Put 'em together and you've probably got something like:

def make_upper(filename, new_filename):
    with open(filename) as infile:
        data = infile.read()
    with open(new_filename) as outfile:
        outfile.write(data.upper())

def main():
    user_in = input("What's the path to your file? ")
    path = user_in # just for clarity
    root, filename = os.path.split(user_in)
    head,tail = os.path.splitext(filename)
    new_filename = "UPPER{}{}".format(head,tail)
    new_path = os.path.join(root, new_filename)
    make_upper(path, new_path)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.