473,566 Members | 3,112 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3223
"hokiegal99 " <ho********@hot mail.com> wrote in message
news:93******** *************** ***@posting.goo gle.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

--
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=filena me[: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=filena me[: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******@spaml ess.rochester.r r.com> wrote:
"hokiegal99 " <ho********@hot mail.com> wrote in message
news:93******* *************** ****@posting.go ogle.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='abcde f' gets you filename[:6] => 'abcdef'
filename='abcde fg' 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("Ente r the path: ")
def truncate(setpat h):
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(ro ot,new_fname)
oldpath = os.path.join(ro ot,old_fname)
os.rename(oldpa th,newpath)
truncate(setpat h)
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.appen d('.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#SECT ION005120000000 000000000>

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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6584
by: Ralph Freshour | last post by:
I have a PHP web app using MySQL - when I save a .jpg file named test's.jpg I see that the filename on the unix server is: test\'s.jpg - the filename I end up saving in my SQL table is named test's.jpg - when I use an image tag to display the photo on my web page, no image displays. I tried to strip the slash out of the filename but the...
3
20978
by: Martin Lucas-Smith | last post by:
Is there some way of using ereg to detect when certain filename extensions are supplied and to return false if so, WITHOUT using the ! operator before ereg () ? I have an API that allows as an input a regular expression, enabling the administrator to ensure a file upload matches a certain pattern. For instance, supplying the string ...
0
1281
by: umesh | last post by:
Hi, I am using MicroSoft.NET Framework 1.1 Version 1.1.4322 on Japanese Windows 2000. In my application, I have given user facility to upload and download the files. If FileName is Japanese and greater than 17 characters, then the filename does not appear in file download dialog box.
2
2888
by: Xam | last post by:
Hello everybody Do you know of a javascript routine that can warn if there are any pre-defined invalid chars in the filename of an INPUT file box before it is submitted with the submit button. The process would be: a) User clicks the INPUT File's Browse button to select the file from their computer.
1
2098
by: CB | last post by:
Using C# in .Net 2003, DataSet.ReadXml fails when a percentage (%) sign is in the filename followed by 2 hex characters. Seems that the % sign is likely encoding the following 2 hex characters. So c:\test%ab.xml fails for ReadXml since %ab is interpreted as 171 and c:\test171.xml does not exist. There is no problem with c:\test%mn.xml...
10
13044
by: Brian Gruber | last post by:
Hi, I'm looking for a way to rename a whole directory of files in short order. The files in the directory have different lengths, however all of them end with _xxxx the x's represent a randomly generated number from a program that I saved from. So I need to find a way that I can quickly remove the underscore and the last 4 numbers from the...
13
7203
by: Bryan Parkoff | last post by:
I have seen that C/C++ Compiler supports long filename up to 254 characters plus the extension. Can header files and source code files accept space between alphabet character and numeric character? Is it the best practice to use underscore instead of space? If so, please explain why. Would you prefer to avoid using two double quote marks...
13
4728
by: dgk | last post by:
I can't find anything in the framework that will tell me whether a filename is valid. I suppose that I can just try to open it and trap an error but that seems wasteful. I dug around and found this code: Public Function IsValidName(ByVal name As String) As Boolean Dim i As Integer For i = 0 To name.Length - 1 Dim ch As Char =...
18
2754
by: RedLars | last post by:
Hi, How can check using .NET 1.1 that a string contains a valid filename for winxp? The application in question has a textbox where user can enter filename and only the filename. It should not allowed to enter path +filename like "c:\tmp\myfile.log" or relative paths "..\tmp \myfile.log" - no directory info should be allowed, only the...
0
7683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7899
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7957
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6270
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5487
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5215
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3647
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3628
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.