0

I need to add a prefix to file names within a directory. Whenever I try to do it though, it tries to add the prefix to the beginning of the file path. That won't work. I have a few hundred files that I need to change, and I've been stuck on this for a while. Have any ideas? Here's the closest I've come to getting it to work. I found this idea in this thread: How to add prefix to the files while unzipping in Python? If I could make this work inside my for loop to download and extract the files that would be cool, but it's okay if this happens outside of that loop.

import os
import glob
import pathlib

for file in pathlib.Path(r'C:\Users\UserName\Desktop\Wells').glob("*WaterWells.*"):
    dst = f"County_{file}"
    os.rename(file, os.path.join(file, dst))

That produces this error:

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg' -> 'C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg\\County_C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg'

I'd like to add "County_" to each file. The targeted files use this syntax: CountyName_WaterWells.ext

2 Answers 2

1

os.path.basename gets the file name, os.path.dirname gets directory names. Note that these may break if your slashes are in a weird direction. Putting them in your code, it would work like this

import os
import glob
import pathlib

for file in pathlib.Path(r'C:\Users\UserName\Desktop\Wells').glob("*WaterWells.*"):
    dst = f"County_{os.path.basename(file)}"
    os.rename(file, os.path.join(os.path.dirname(file), dst))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. That is exactly what I needed. I haven't explored the os library a lot, but it looks like I'll have to check things out more. I'm working with a lot of different datasets and it seems like the stuff in os will really come in handy.
1

The problem is your renaming variable, dst, adds 'County_' before the entire path, which is given by the file variable.

If you take file and break it up with something like file.split("/") (where you should replace the slash with whatever appears between directories when you print file to terminal) then you should be able to get file broken up as a list, where the final element will be the current filename. Modify just this in the loop, put the whole thing pack together using "".join(_path + modified_dst) and then pass this to os.rename.

Comments

Your Answer

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.