Determining if a filename is greater than X characters

hokiegal99 hokiegal99 at vt.edu
Sun Aug 3 17:42:01 EDT 2003


OK, I'll use spaces... I thought tabs akward, but they take less time in 
my editor than spaces do. Thanks for the for loop idea. It works 
perfectly. Below is the script with spaces instead of tabs. Thanks again!!!

import os
print " "
setpath = raw_input("Enter the path: ")
def truncate(setpath):
    for root, dirs, files in os.walk(setpath):
       old_fname = files
       for old_fname in files:
          new_fname = old_fname[:27]
#        print old_fname
#        print new_fname
          if new_fname != old_fname:
             print "file: ",old_fname," truncated to: ",new_fname
             newpath = os.path.join(root,new_fname)
             oldpath = os.path.join(root,old_fname)
             os.rename(oldpath,newpath)
truncate(setpath)


Alex Martelli wrote:
> hokiegal99 wrote:
> 
> 
>>Thanks for the tips. I got it to work using this:
>>
>>for root, dirs, files in os.walk(setpath):
>>old_fname = files
>>new_fname = old_fname[0][:27]
>>print old_fname
>>print new_fname
> 
> 
> [note the lack of indentation due to your usage of tabs -- please use
> spaces, not tabs, for Python code in messages you post to the net or send by
> mail - many popular user-agents for news and mail, such as Microsoft
> Outlook Express and KDE's KNode, won't display or process tabs in the
> way you might expect them to].
> 
> 
> 
>>The problem with this approach is that it only gets the first filename
>>in the directory. I tried doing "old_fname[:][:27]", but that doesn't do
>>it. I need to learn more about lists.
> 
> 
> Since files is a LIST of strings, you may loop (directly or with a
> list-comprehension) to process all of its items, i.e., your loop
> above becomes:
> 
> for root, dirs, files in os.walk(setpath):
>     for old_fname in files:
>         new_fname = old_fname[:27]
>         print old_fname
>         print new_fname
> 
> 
> Alex
> 






More information about the Python-list mailing list