469,336 Members | 5,276 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,336 developers. It's quick & easy.

Determining if a filename is greater than X characters

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!!!
Jul 18 '05 #1
11 2945
"hokiegal99" <ho********@hotmail.com> wrote in message
news:93**************************@posting.google.c om...
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/
Jul 18 '05 #2
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.
Jul 18 '05 #3
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

Jul 18 '05 #4
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

Jul 18 '05 #5
On Sun, 03 Aug 2003 02:45:31 GMT, "Cy Edmunds" <ce******@spamless.rochester.rr.com> wrote:
"hokiegal99" <ho********@hotmail.com> wrote in message
news:93**************************@posting.google. com...
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
Jul 18 '05 #6
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

Jul 18 '05 #7
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

Jul 18 '05 #8
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!!!

Jul 18 '05 #9
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/>
Jul 18 '05 #10
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

Jul 18 '05 #11
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

Jul 18 '05 #12

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Martin Lucas-Smith | last post: by
10 posts views Thread by Brian Gruber | last post: by
13 posts views Thread by Bryan Parkoff | last post: by
18 posts views Thread by RedLars | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by Marylou17 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.