Determining if a filename is greater than X characters

Discussion in 'Python' started by hokiegal99, Aug 3, 2003.

  1. hokiegal99

    hokiegal99 Guest

    How would I determine if a filename is greater than a certain number
    of characters and then truncate it to that number? For example a file
    named XXXXXXXXX.txt would become XXXXXX

    fname = files
    if fname[0] > 6
    print fname[0]

    Thanks!!!
    hokiegal99, Aug 3, 2003
    #1
    1. Advertising

  2. hokiegal99

    Cy Edmunds Guest

    "hokiegal99" <> wrote in message
    news:...
    > How would I determine if a filename is greater than a certain number
    > of characters and then truncate it to that number? For example a file
    > named XXXXXXXXX.txt would become XXXXXX
    >
    > fname = files
    > if fname[0] > 6
    > print fname[0]
    >
    > Thanks!!!


    filename = "abcdefgh"
    if len(filename) > 6:
    filename = filename[:6]
    print filename
    abcdef

    --
    Cy
    http://home.rochester.rr.com/cyhome/
    Cy Edmunds, Aug 3, 2003
    #2
    1. Advertising

  3. On Saturday 02 August 2003 19:15, hokiegal99 wrote:
    > How would I determine if a filename is greater than a certain number
    > of characters and then truncate it to that number? For example a file
    > named XXXXXXXXX.txt would become XXXXXX
    >
    > fname = files
    > if fname[0] > 6
    > print fname[0]
    >
    > Thanks!!!


    look at the os.path module and also the len() builtin. The two of those
    should give you everything you need.
    Sean 'Shaleh' Perry, Aug 3, 2003
    #3
  4. Cy Edmunds wrote:

    > filename = "abcdefgh"
    > if len(filename) > 6:
    > filename = filename[:6]
    > print filename
    > abcdef


    The if is not necessary, just use

    filename=filename[:6]

    --Irmen
    Irmen de Jong, Aug 3, 2003
    #4
  5. slicing is "fail-soft" (was Re: Determining if a filename is greater than X characters)

    Irmen de Jong wrote:

    > Cy Edmunds wrote:
    >
    >> filename = "abcdefgh"
    >> if len(filename) > 6:
    >> filename = filename[:6]
    >> print filename
    >> abcdef

    >
    > The if is not necessary, just use
    >
    > filename=filename[:6]


    Right. To reiterate the point, which IS very important: differently from
    indexing, slicing is FAIL-SOFT -- if you ask for nonexistent parts of a
    sequence as part of a slice, you'll just get a shorter resulting sequence
    from your slicing. This often makes for smoother code because less guards
    are necessary.

    For example, say that I want to check if "the string is non-empty and its
    first character is alphabetical". Coding this as:

    if thestring and thestring[0].isalpha():

    is one obvious way -- but a smooth alternative is:

    if thestring[0:1].isalpha():

    If the string IS empty, so will thestring[0:1] be (and such a slicing out of
    the sequence's boundaries raises NO exception, which is the key point), and
    ''.isalpha() is False (easy to remember: ''.isXYZ() is False for all
    supported XYZ:), so these conditions are equivalent.


    Alex
    Alex Martelli, Aug 3, 2003
    #5
  6. On Sun, 03 Aug 2003 02:45:31 GMT, "Cy Edmunds" <> wrote:

    >"hokiegal99" <> wrote in message
    >news:...
    >> How would I determine if a filename is greater than a certain number
    >> of characters and then truncate it to that number? For example a file
    >> named XXXXXXXXX.txt would become XXXXXX
    >>
    >> fname = files
    >> if fname[0] > 6
    >> print fname[0]
    >>
    >> Thanks!!!

    >
    >filename = "abcdefgh"
    >if len(filename) > 6:
    > filename = filename[:6]
    >print filename
    >abcdef


    Why the if test?

    >>> for filename in ['abcdefgh'[:i] for i in range(8)]:

    ... print 'filename=%r gets you filename[:6] => %r' % (filename, filename[:6])
    ...
    filename='' gets you filename[:6] => ''
    filename='a' gets you filename[:6] => 'a'
    filename='ab' gets you filename[:6] => 'ab'
    filename='abc' gets you filename[:6] => 'abc'
    filename='abcd' gets you filename[:6] => 'abcd'
    filename='abcde' gets you filename[:6] => 'abcde'
    filename='abcdef' gets you filename[:6] => 'abcdef'
    filename='abcdefg' gets you filename[:6] => 'abcdef'

    I wonder about the application of this for filenames though, since filenames
    often share prefixes.

    Regards,
    Bengt Richter
    Bengt Richter, Aug 3, 2003
    #6
  7. 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
    Alex Martelli, Aug 3, 2003
    #7
  8. hokiegal99

    hokiegal99 Guest

    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
    >
    hokiegal99, Aug 3, 2003
    #8
  9. hokiegal99

    hokiegal99 Guest

    One last question and then I'll leave you guys alone for awhile: How
    would I append a string to the end of each file that I've truncated? I'd
    like to put '.txt' on the end, but I don't understand how to go about
    it. When I tried this:

    old_fname = files
    new_fname = old_fname.append('.txt')

    ..txt was added as a string to the files list. Researching a bit on
    Google told me that in Python strings are unchangeable. So, how would I
    go about changing a string?

    Thanks!!!


    hokiegal99 wrote:
    > How would I determine if a filename is greater than a certain number
    > of characters and then truncate it to that number? For example a file
    > named XXXXXXXXX.txt would become XXXXXX
    >
    > fname = files
    > if fname[0] > 6
    > print fname[0]
    >
    > Thanks!!!
    hokiegal99, Aug 4, 2003
    #9
  10. hokiegal99

    Ben Finney Guest

    On Sun, 03 Aug 2003 22:30:27 -0400, hokiegal99 wrote:
    > How would I append a string to the end of each file that I've
    > truncated?


    The concatenation operator for strings is '+':

    <http://www.python.org/doc/current/tut/node5.html#SECTION005120000000000000000>

    It would behoove you to work through the Python tutorial all the way, to
    get a solid grounding in the language:

    <http://www.python.org/doc/current/tut/>

    > Researching a bit on Google told me that in Python strings are
    > unchangeable.


    You're probably reading the word "immutable" (which, in English, means
    pretty much the same thing, so the confusion is understandable).

    String objects can't be changed (they are immutable), but you can bind
    the name (the "variable") to a new string object, thus changing the
    value referred to by the name.

    Same thing happens when you perform arithmetic on a name bound to an
    integer object:

    >>> foo = 1
    >>> foo

    1
    >>> foo = foo + 2
    >>> foo

    3
    >>>


    What's happening here? The name 'foo' is being bound to the integer
    object '1'. Then a new integer object is created with value '3' (as a
    result of the arithmetic) and the name 'foo' is bound to the new object
    (as a result of the assignment).

    Thus, integer objects are immutable, but the name can be bound to a new
    object with a different value by an assignment operation.

    At the level of strings and integers, the distinction between "string
    objects can be changed by assigning a new value" (incorrect) and "string
    objects are immutable, assignment binds to a new object" (correct) seems
    to make no difference. If you learn this, though, other aspects of
    object behaviour will be much easier to understand.

    --
    \ "If you're a horse, and someone gets on you, and falls off, and |
    `\ then gets right back on you, I think you should buck him off |
    _o__) right away." -- Jack Handey |
    Ben Finney <http://bignose.squidly.org/>
    Ben Finney, Aug 4, 2003
    #10
  11. hokiegal99 wrote:

    > One last question and then I'll leave you guys alone for awhile: How
    > would I append a string to the end of each file that I've truncated? I'd
    > like to put '.txt' on the end, but I don't understand how to go about
    > it. When I tried this:
    >
    > old_fname = files
    > new_fname = old_fname.append('.txt')
    >
    > .txt was added as a string to the files list. Researching a bit on
    > Google told me that in Python strings are unchangeable. So, how would I
    > go about changing a string?


    You cannot change a given string-object, any more than you can change
    a given number-object -- the object 23 will always have value 23 (never
    22 nor 24 nor any other number), the object 'foo' will always have
    value 'foo' (never 'bar' nor 'foobar' nor any other string).

    However, you can re-bind a name to refer to a different object than
    the one it previously referred to. Thus, for example:

    x = 23
    x = x + 1

    this has not changed the number 23, whose value IS still 23, but name
    x now refers to a different number, namely, the number 24. Similarly:

    x = 'foo'
    x = x + '.txt'

    this has not changed the string 'foo', whose value IS still 'foo', but name
    x now refers to a different string, namely, the string 'foo.txt'.

    The unchangeability of strings doesn't inhibit string manipulation any
    more than the unchangeability of numbers inhibits arithmetics. Simply,
    operations on strings build and return new strings, just like operations
    on numbers build and return new numbers, and in either case you may, if
    you wish, re-bind some pre-existing name to refer to the new objects.


    Alex
    Alex Martelli, Aug 4, 2003
    #11
  12. hokiegal99 wrote:

    > 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!!!


    You're welcome! Note that good editors can be configured so as to let
    you hit the Tab keys for indentation (and shift-Tab to go back, if you
    wish) while using spaces in the file as saved. If your current editor
    does not support that I would suggest you consider changing -- there
    are SO many good editors out there, after all. For example, IDLE, the
    integrated GUI development environment that comes with Python, is quite
    nice now in its release 1.0 (comes with Python 2.3). The Options menu
    opens a multi-tab dialog open at the first tab, "Fonts/Tabs", and you'll
    see a simple choice between "Tab key inserts spaces" (default) and an
    alternative of "Tab key inserts tabs". Even though I normally use VIM
    myself (a highly configurable & programmable descendant of good old vi)
    and occasionally SciTE (a useful lightweight editor/environment), I'm
    seriously tempted by the new IDLE 1.0 to switch for much of my work...


    Alex
    Alex Martelli, Aug 4, 2003
    #12
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ryan
    Replies:
    1
    Views:
    511
  2. falcon
    Replies:
    10
    Views:
    18,637
    Roedy Green
    Feb 24, 2006
  3. Alf P. Steinbach

    isdigit() for characters greater than 127

    Alf P. Steinbach, Oct 9, 2004, in forum: C++
    Replies:
    4
    Views:
    3,222
    James Gregory
    Oct 9, 2004
  4. Replies:
    6
    Views:
    397
  5. Dwight Army of Champions
    Replies:
    4
    Views:
    2,742
    John H.
    Mar 17, 2010
Loading...

Share This Page