Determining if a filename is greater than X characters

H

hokiegal99

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

Cy Edmunds

hokiegal99 said:
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
 
S

Sean 'Shaleh' Perry

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.
 
I

Irmen de Jong

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

The if is not necessary, just use

filename=filename[:6]

--Irmen
 
A

Alex Martelli

Irmen said:
Cy said:
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
 
B

Bengt Richter

hokiegal99 said:
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
 
A

Alex Martelli

hokiegal99 said:
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
 
H

hokiegal99

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 said:
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
 
H

hokiegal99

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

Ben Finney

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:

said:
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:

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.
 
A

Alex Martelli

hokiegal99 said:
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
 
A

Alex Martelli

hokiegal99 said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top