iwishiwasaneagle
iwishiwasaneagle

Reputation: 321

Automatically detecting file extensions

As you can see this is very very clunky. How would I go about automatically detecting file extension?

txt_files = glob('*txt')
png_files = glob('*.png')
jpg_files = glob('*.jpg')
zip_files = glob('*.zip')
gif_files = glob('*.gif')
iso_files = glob('*iso')
epub_files = glob('*epub')
ico_files = glob('*.ico')

#Unimportant bit to question

for n in txt_files:
    move_files(n, 'txt')
for n in png_files:
    move_files(n, 'png')
for n in jpg_files:
    move_files(n, 'jpg')
for n in zip_files:
    move_files(n, 'zip')
for n in gif_files:
    move_files(n, 'gif')
for n in iso_files:
    move_files(n, 'iso')
for n in epub_files:
    move_files(n, 'epub')
for n in ico_files:
    move_files(n, 'ico')

Upvotes: 1

Views: 299

Answers (2)

abarnert
abarnert

Reputation: 365637

To "automatically detect new extensions", just go through all the files and look at their extensions:

for f in os.listdir():
    name, ext = os.path.splitext(f)
    ext = ext.lstrip('.')
    if ext:
        os.mkdirs(ext)
        move_file(filename, ext)

Note that this won't work if some of your "extensions" aren't actually extensions. I notice that your existing code searches for things like *txt and *iso, which will of course match stuff like this_is_not_txt and spam.aniso and so forth. If that's a required feature rather than a bug, then you're going to have to come up with some rule for what you mean by "extension" before you can implement it in code…

Also notice that files without an extension at all will be left where they are (because of that if ext:), and files with an empty extension (just .) will be as well (because the if check happens after the lstrip). You can of course change either of those if desired (although you'll need to come up with a subdirectory name that can't possibly be ambiguous with any possible actual extension…).

Finally, this won't handle "double extensions"—for example, .tar.gz files will go into the same directory as .gz. Again, this is easy to change if desired.

Upvotes: 4

Joran Beasley
Joran Beasley

Reputation: 113940

for ext in "txt png jpg zip gif iso epub ico".split():
    for file in glob("*.%s"%ext): #if there are no files of this type it just skips it
        move_files(file,ext)

maybe? its not very clear what your question is

In some sense this is "auto detected" since if there are no files that fit the pattern it will skip the move_files step

Upvotes: 0

Related Questions