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!!! 11 3241
"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/
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.
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
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
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
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
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
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!!!
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/> This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 image still
won't display on the web page - maybe I'm all goofed up here and don't
understand what's...
|
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
'.exe$|.com$|.bat$|.zip$|.doc$'
|
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.
|
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.
|
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
because "mn" is not a hex code. If I replace the % sign with %25
(25hex = 37dec = ascii code for %),...
| |
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 filename
without changing anything else. I can't set a max length to the file
becuase the filename's...
|
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 in the long
filename if space is there? Without it, it would be underspace.
For example:
|
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 = name.Chars(i)
Dim uc As Globalization.UnicodeCategory =
|
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 filename.
|
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 usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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 into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |