jice 53 Posting Whiz in Training

I don't know about this tool but i would guess that the script tries to delete an opened file (is it a zip file or a file inside a zip file, i don't know)

jice 53 Posting Whiz in Training

Sorry, my first post is not good. yours was the good one.
You can do this too :

self.cursor.execute("INSERT INTO DatabaseName (C1, C2, C3, C4, C5) SELECT (%s, C2, C3, C4, C5) FROM DatabaseName WHERE C1='%s'" % (newC1Value, copiedC1Value))
jice 53 Posting Whiz in Training

I'd write

self.cursor.execute("INSERT INTO DatabaseName (C1, C2, C3, C4, C5) SELECT (C1, C2, C3, C4, C5) FROM DatabaseName WHERE C1='%s'", [newC1Value])
jice 53 Posting Whiz in Training

I would just add one last thing about string formating :
if you write something like :

print ("%s is %d years old and wears a %s suit" % (name, age, color))

it is easier to read, to write and to maintain than

print (name + " is " + str(age) + " years old and wears a " + color + " suit")
jice 53 Posting Whiz in Training

You can try this :

fileName = raw_input("Enter the file name you want to read (name.txt): ")
comments=[]
inComment=False
for i, line in enumerate(open(filename)): # You can loop directly on the file lines
    if "//***" in line:
        inComment = not inComment
    if inComment:
        print "comment found at line %d" %i
        comments.append((i, line)) # you store the line and its number
jice 53 Posting Whiz in Training
jice 53 Posting Whiz in Training

Only for the Unix version, I havent found it in the binary version

??
I'm on windows and it's in. I use 2.4.

jice 53 Posting Whiz in Training

Also, for the GUI, you have tkinter and wxPython. tkinter is a little old, so wxPython is the order of the day! ;)

But tkInter is included in the standard distribution...

jice 53 Posting Whiz in Training

You should not remove elements from a list you are looping on

list=[1,2,3,4,5,6,7,8,9]
for i in list:
    if i in [4,5,6]:
        list.remove(i)
print list

> [1, 2, 3, 5, 7, 8, 9]

When you remove an element, the followings ranks are modified (minus 1) so some elements are never used (those that takes the ranks of removed elements).
You have to loop on a copy of your list :

list=[1,2,3,4,5,6,7,8,9]
for i in list[:]: # list[:] is a copy of list...
    if i in [4,5,6]:
        list.remove(i)
print list

> [1, 2, 3, 7, 8, 9]
nunos commented: Excellent post! Very simple and clarifying. +1
jice 53 Posting Whiz in Training

About the hundreds of files, if they are in the same directory, you can use :

import os
for filename in os.listdir(path):
    for line in open(filename): # this avoids the loading of the whole file in memory...
        ...

If they are not, you shoud take a look to os.walk()
If you want to filter your files, you can use the fnmatch module...

jice 53 Posting Whiz in Training

Here is a solution...

datas="""2 1 863.8 300.2 0.0131 0.0759 0.1727 0.0879 1.5821
3 1 874.5 289.5 0.0574 0.1292 0.4447 0.2258 1.1846
3 2 874.5 289.5 0.0573 0.0527 1.0857 0.1684 1.1760
4 1 844.3 319.7 0.1306 1.3513 0.0967 1.3976 2.2659
4 2 849.2 314.8 0.1350 1.3332 0.1013 1.3773 1.9990
4 3 846.0 318.0 0.1546 1.4675 0.1053 1.5399 2.1172""".split("\n")
tags="""1 PAA_888    
2 PAD_999
3 PAB_978
4 PCA_098""".split("\n")
dtags={}
# load tags in a dictionary :
for l in tags:
    t=l.split()
    dtags[t[0]]=t[1]

# print datas
for l in datas:
    sl=l.split()
    if float(sl[5]) > 1:
        print sl[0], dtags[sl[0]], sl[1], dtags[sl[1]], sl[5]
jice 53 Posting Whiz in Training

You can get rid of encryption by converting your file to ps and back to pdf (using ghostscript for example).

jice 53 Posting Whiz in Training

you should use :

>>> mystring[13:0:-1]
'!dlroW ,olle'

But the first letter isn't taken as the second parameter of the slice is to be excluded... To have the first letter (H), you'll need to do

>>> mystring[13::-1]
'!dlroW ,olleH'
jice 53 Posting Whiz in Training

use fnmatch module to filter :
http://docs.python.org/library/fnmatch.html
os.rename to move your file

jice 53 Posting Whiz in Training

You can do more efficient :

sql = "SELECT Name FROM nameDatabase"
self.cursor.execute(sql)
list=[element[0] for element in self.cursor.fetchall()]
print list
jice 53 Posting Whiz in Training
if not ignore:
	   	new_list.append(line)
jice 53 Posting Whiz in Training

Is there any other way to do like this?

Maybe... the best would be you tell me what doesn't suit you in this way so that I could adapt this script...

But, with what you told, this is certainly the best way I can see :
- you can have any number od databases,
- you can store whatever parameter you want for each database (here, the connexion and the cursor but it could be anything else)
- easy to use after...

Here is another idea. Instead of a list of DB, you have a dictionnary which has ip adresses for keys :

dbDic={}
for ip in ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4']:
    cnx=MySQLdb.connect(host=ip, user='root', db='navicat')
    cur=cnx.cursor()
    dbDic[ip]={'cnx':cnx, 'cur':cur}
jice 53 Posting Whiz in Training

You can try something like this :

dbLst=[]
for ip in ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4']:
    cnx=MySQLdb.connect(host=ip, user='root', db='navicat')
    cur=cnx.cursor()
    dbLst.append({'cnx':cnx, 'cur':cur})

And please, if you post code wrap it between tags (see my preceeding post)

jice 53 Posting Whiz in Training

could you put tags aroud your code, please ?
[ code=python]
your code here
[ /code]

2d point, I don't understand what you are doing

ip = 8
while(ip <= 9):
cxn1 = MySQLdb.connect(host='10.0.2.9',host='192.168.1.2', db='navicat')
cur1 = cxn1.cursor()
cxn = MySQLdb.connect(user='root',db='navicat')
cur = cxn.cursor()

You don't use ip variable, nor do you increment it.
cnx1 has 2 hosts but no user

jice 53 Posting Whiz in Training

you inverted targetlines[1] and targetlines[2]

jice 53 Posting Whiz in Training

OUPS

def new_rec_list(rec_in, dic_return):
   conditions = rec_in.split()
   name, key = conditions[0].split("=")   ## split first one only
   dic_return[key]= {}                     ## empty dictionary
        
   stop = len(conditions)
   for num in range(1, stop):
      sub_conditions = conditions[num].split("=")  ## a list with 2 elements
      # dic_return[key].update(dict([conditions[num]]))
      dic_return[key].update(dict([sub_conditions])) # another way
   return dic_return, key

This should be better

jice 53 Posting Whiz in Training

Here are some clues to make a dictionary :

For example, your append_rec_list function :

def append_rec_list(rec_in, return_dic, key):
   conditions = rec_in.split()
   for each_c in conditions:
      sub_conditions = each_c.split("=")  ## a list with 2 elements
      return_dic[key].append(sub_conditions)
   return return_dic

will become

def append_rec_list(rec_in, return_dic, key):
   conditions = rec_in.split()
   for each_c in conditions:
      sub_conditions = each_c.split("=")  ## a list with 2 elements
      if len(sub_conditions)==2:
          return_dic[key].update({sub_conditions[0]:sub_conditions[1]})
      elif len(sub_conditions)==1: # if you need this...
          return_dic[key].update({"idx":sub_conditions[0]})
   return return_dic

and

def new_rec_list(rec_in, dic_return):
   conditions = rec_in.split()
   name, key = conditions[0].split("=")   ## split first one only
   dic_return[key]= []                     ## empty list
        
   ##   process element #2 through the end of the list
   stop = len(conditions)
   for num in range(1, stop):
      sub_conditions = conditions[num].split("=")  ## a list with 2 elements
      dic_return[key].append(sub_conditions)
   return dic_return, key

will become

def new_rec_list(rec_in, dic_return):
   conditions = rec_in.split()
   name, key = conditions[0].split("=")   ## split first one only
   dic_return[key]= {}                     ## empty dictionary
        
   stop = len(conditions)
   for num in range(1, stop):
      sub_conditions = conditions[num].split("=")  ## a list with 2 elements
      dic_return[key].update(dict([conditions[num]])) # another way to make the dictionary... But you can do as in the append function
   return dic_return, key

This haven't been tested as I don't have any file to process and i don't want to build one :)

jice 53 Posting Whiz in Training

If you need it, here are your dictionaries translated (vim powa)

Material_dic: {'STEEL': {'IDES':'S', 'W':'76819.41', 'T':'0', 'E':'1.99948E+11', 'U':'.3', 'A':'.0000117', 'FY':'3.447379E+08'}, 'S335': {'IDES':'S', 'W':'78500.3', 'T':'0', 'E':'2.05E+11', 'U':'.3', 'A':'.0000117', 'FY':'3.35E+08'}, 'OTHER': {'IDES':'N', 'W':'76819.55', 'T':'0', 'E':'1.99948E+11', 'U':'.3', 'A':'.0000117'}, 'S345': {'IDES':'S', 'W':'78500.3', 'T':'0', 'E':'2.05E+11', 'U':'.3', 'A':'.0000117', 'FY':'3.45E+08'}, 'S355': {'IDES':'S', 'W':'78500.27', 'T':'0', 'E':'2.05E+11', 'U':'.3', 'A':'.0000117', 'FY':'3.557E+08'}, 'GLASS': {'IDES':'C', 'W':'26000', 'T':'0', 'E':'7.2E+10', 'U':'.235', 'A':'.000008'}, 'CONC': {'IDES':'C', 'W':'23561.61', 'T':'0', 'E':'2.482113E+10', 'U':'.2', 'A':'.0000099'}, 'S325': {'IDES':'S', 'W':'78500.3', 'T':'0', 'E':'2.05E+11', 'U':'.3', 'A':'.0000117', 'FY':'3.25E+08'}, 'MAC520': {'IDES':'S', 'W':'76820', 'T':'0', 'E':'2.482113E+10', 'U':'.3', 'A':'.0000117', 'FY':'5.2E+08'}, 'LWC': {'IDES':'C', 'W':'19000', 'T':'0', 'E':'2.482E+10', 'U':'.2', 'A':'.0000099'}}

Frame_Section_dic: {'LCHS610-25-4': {'MAT':'S355', 'SH':'P', 'T':'.61,.0254'}, 'F500X250X10X17': {'MAT':'S355', 'SH':'I', 'T':'.5,.25,.017,.01,.25,.017'}, 'F500X250X10X15': {'MAT':'S355', 'SH':'I', 'T':'.5,.25,.015,.01,.25,.015'}, '356X406X551UCWITH80PLATES': {'MAT':'S325', 'SH':'B', 'T':'.4556,.5785,.0675,.08'}, 'UC356X368X129': {'MAT':'STEEL', 'A':'.0164', 'J':'1.53E-06', 'I':'.0004025,.0001461', 'AS':'3.69824E-03,1.075083E-02', 'S':'2.26378E-03,7.927293E-04', 'Z':'.00248,.0012', 'R':'.156661,9.438504E-02', 'T':'.3556,.3686,.0175,.0104,.3686,.0175', 'SHN':'UC356X368X129', 'DSG':'W'}, 'UB305X165X46': {'MAT':'STEEL', 'A':'.00587', 'J':'2.22E-07', 'I':'9.899E-05,8.96E-06', 'AS':'2.05422E-03,3.258767E-03', 'S':'6.457273E-04,1.081473E-04', 'Z':'.00072,.000166', 'R':'.1298604,3.906924E-02', 'T':'.3066,.1657,.0118,.0067,.1657,.0118', 'SHN':'UB305X165X46', 'DSG':'W'}, 'UB305X165X40': {'MAT':'STEEL', 'A':'.00513', 'J':'1.47E-07', 'I':'8.503E-05,7.64E-06', 'AS':'.0018204,.002805', 'S':'5.605142E-04,9.260606E-05', 'Z':'.000623,.000142', 'R':'.1287441,3.859118E-02', 'T':'.3034,.165,.0102,.006,.165,.0102', 'SHN':'UB305X165X40', 'DSG':'W'}, 'LCHS965-22-2': {'MAT':'S355', 'SH':'P', 'T':'.965,.0222'}, 'LCHS914-32': {'MAT':'S355', 'SH':'P', 'T':'.914,.032'}, 'UC356X406X340': {'MAT':'STEEL', 'A':'.0433', 'J':'2.343E-05', 'I':'.001225,.0004685', 'AS':'1.081024E-02,.0288145', 'S':'6.028544E-03,2.325062E-03', 'Z':'.007,.00354', 'R':'.1681993,.1040186', 'T':'.4064,.403,.0429,.0266,.403,.0429', 'SHN':'UC356X406X340', 'DSG':'W'}, 'UC254X254X107': {'MAT':'STEEL', 'A':'.0136', 'J':'1.72E-06', 'I':'.0001751,5.928E-05', 'AS':'3.41376E-03,8.842333E-03', 'S':'1.313086E-03,4.581144E-04', 'Z':'.00148,.000697', 'R':'.1134681,6.602139E-02', 'T':'.2667,.2588,.0205,.0128,.2588,.0205', 'SHN':'UC254X254X107', 'DSG':'W'}, 'UB254X146X37': {'MAT':'STEEL', 'A':'.00472', 'J':'1.53E-07', 'I':'5.537E-05,5.71E-06', 'AS':'.0016128,.0026596', 'S':'4.325781E-04,7.800547E-05', 'Z':'.000483,.000119', 'R':'.1083094,.0347814', 'T':'.256,.1464,.0109,.0063,.1464,.0109', 'SHN':'UB254X146X37', 'DSG':'W'}, 'F500X220X10X15': {'MAT':'S355', 'SH':'I', 'T':'.5,.22,.015,.01,.22,.015'}, 'T': {'MAT':'STEEL', 'SH':'I', 'T':'.18,.01,.01,.008,.2,.01'}, 'UC305X305X118': {'MAT':'STEEL', 'A':'.015', 'J':'1.61E-06', 'I':'.0002767,9.059E-05', 'AS':'.003774,9.580634E-03', 'S':'1.759618E-03,5.893949E-04', 'Z':'.00196,.000895', 'R':'.1358185,7.771315E-02', 'T':'.3145,.3074,.0187,.012,.3074,.0187', 'SHN':'UC305X305X118', 'DSG':'W'}, 'UC305X305X198': {'MAT':'STEEL', 'A':'.0252', 'J':'7.34E-06', 'I':'.000509,.000163', 'AS':'6.49209E-03,1.645883E-02', 'S':'2.994999E-03,1.036566E-03', 'Z':'.00344,.00158', 'R':'.1421211,8.042546E-02', 'T':'.3399,.3145,.0314,.0191,.3145,.0314', 'SHN':'UC305X305X198', 'DSG':'W'}, 'LCHS813-15-9': {'MAT':'S355', 'SH':'P', 'T':'.813,.0159'}, 'CS300X100X46': {'MAT':'S355', 'SH':'C', 'T':'.3,.1,.0165,.009'}, 'UC356X406X467': {'MAT':'STEEL', 'A':'.0595', 'J':'5.809E-05', 'I':'.00183,.0006783', 'AS':'1.563028E-02,.039846', 'S':'8.382958E-03,3.291121E-03', 'Z':'.01,.00503', 'R':'.1753747,.1067708', 'T':'.4366,.4122,.058,.0358,.4122,.058', 'SHN':'UC356X406X467', 'DSG':'W'}, 'FAB50': {'MAT':'S355', 'SH':'I', 'T':'.5,.16,.015,.012,.16,.015'}, 'F500X160X10X10': {'MAT':'S355', 'SH':'I', 'T':'.5,.16,.01,.01,.16,.01'}, 'F500X160X10X12': {'MAT':'S355', 'SH':'I', 'T':'.5,.16,.012,.01,.16,.012'}, …
jice 53 Posting Whiz in Training

This is because of the structure of your dictionnary : as you use something like
dic={KEY1:[[key1, val1], [key2, val2]], KEY2:[...]}
I used something like
dic={KEY1:{key1:val1, key2:val2},KEY2:{...}}
(look carefully my first post about that)

The way you built your dictionnary is certainly not very far from the way you can build mine.
But, in this case, mine is much easier to use because 'IDES', 'T,' 'E'... are keys and not only the first element of a list so you can do
value=dic[KEY1][key2]
instead of

for element in dic[KEY1]:
    if element[0]==key2:
        value=element[1]
        break
jice 53 Posting Whiz in Training

deleted - I had a cache problem

jice 53 Posting Whiz in Training

I looked at your code.
As far as I could go (as I can't execute everything) is that you call a function without having defined the parameters :

section_material_read(Shell_Section_dic,Frame_Section_dic,Material_dic)

At this point of your program, these variables (Shell_Section_dic, Frame_Section_dic, Material_dic) are not defined yet.
Simply do this here rather than in the section_material_read function :

Shell_Section_dic = {}
Frame_Section_dic = {}
Material_dic = {}
section_material_read(Shell_Section_dic,Frame_Section_dic,Material_dic)

and this error will normally disapear

As I could see your code, my advice would be :

don't put a function def, then some standalone lines of code then some function def again and some more standalone lines then other functions...
This makes your code hard to follow.

Put all your code in short functions (if not in classes) and, at the end of your file, one function call. That's all.
A good program is a well organised program. If not well organised, your program will never be able to grow properly.

good luck

jice 53 Posting Whiz in Training

Here is a way to process you file.
This is just a quick example that you'll have to adapt.
The idea is to store the section of the file you're in and then adapt the line processing depending on the section.

datas = """
NAME=LIVE
TYPE=UNIFORM
ADD=110 UZ=-4500
ADD=113 UZ=-4500
ADD=114 UZ=-4500
ADD=120 UZ=-4500
ADD=121 UZ=-4500

NAME=SIDL
TYPE=UNIFORM
ADD=110 UZ=-850
ADD=113 UZ=-850

and will realise that the part
NAME=LIVE
TYPE=UNIFORM
ADD=110 UZ=-4500
ADD=113 UZ=-4500
ADD=114 UZ=-4500
ADD=120 UZ=-4500
ADD=121 UZ=-4500
"""
section='' # which part of the file are we in
for line in datas.split('\n'): # depends on the way datas are presented maybe "from line in file("/path/to/file.txt"):"
    if 'LOAD' in line:
        print "Process LOAD line"
        section = 'LOAD'
    elif 'NAME' in line:
        section=line.strip('\n').split("=")[1] # the section name is the second part of the line
                            # (without the '\n' at the end), splitted with the "="  and
                            # where the first part is NAME
    else:
        if section == 'LIVE':
            print "process %s\n%s" % (section, line)
        elif section == 'SIDL':
            print "process %s\n%s" % (section, line)
jice 53 Posting Whiz in Training

haha, you did some copy errors :

Hi, Jice

if 'NSEG' in line1 and 'ANG' in line1:
            dResult={}
            targetlines=["*beam section,section=R, elset=%s, material=%s",
                         "%s",
                         "%f, %f, %f"]
             
            for elt in line1.split():
                keyValue=elt.split('=')   ##seperate key from value    

                if len(keyValue) == 2:
                    dResult[keyValue[0]]=keyValue[1]
            ####################################
            # HERE you deleted the try statement without correct
            # the indent (this should be 4 spaces left, like this : )
            ####################################
            mat_data=Frame_Section_dic[dResult['SEC']]['MAT']
            T_data=Frame_Section_dic[dResult['SEC']]['T']
            resultlines=[targetlines[0] % (dResult['SEC'],mat_data),
                         targetlines[1] % T_data,
                         targetlines[2] % (math.sin(float(dResult['ANG'])*math.pi/180),
                                           math.cos(float(dResult['ANG'])*math.pi/180),
                                           0)]
            for line9 in resultelines:
                binf.write(line9)

But I'm not sure your error comes from this code...
It means that your Frame_Section_dic is not created before you use it (something like var=Frame_Section_dic[...]) when you modify your line.
But, as your code isn't complete, I can't see where this occurs (you can send me your whole code in PM if you want a more complete advise)
Anyway, try the correction I've posted and tell me if this works :)

jice 53 Posting Whiz in Training

I just put tags to see your code properly rendered

Hi, Jice

The error is simple

Traceback (most recent call last):
File "<pyshell#25>", line 1, in -toplevel-
Frame_Section_dic
NameError: name 'Frame_Section_dic' is not defined

My code is a copy of your code below

if 'NSEG' in line1 and 'ANG' in line1:
            dResult={}
            targetlines=["*beam section,section=R, elset=%s, material=%s",
                         "%s",
                         "%f, %f, %f"]
             
            for elt in line1.split():
                keyValue=elt.split('=')   ##seperate key from value    

                if len(keyValue) == 2:
                    dResult[keyValue[0]]=keyValue[1]
                mat_data=Frame_Section_dic[dResult['SEC']]['MAT']
 #               print "mat_data=:", mat_data
                T_data=Frame_Section_dic[dResult['SEC']]['T']
 #               print "T_data=:", T_data
                resultlines=[targetlines[0] % (dResult['SEC'],mat_data),
                             targetlines[1] % T_data,
                             targetlines[2] % (math.sin(float(dResult['ANG'])*math.pi/180),
                                               math.cos(float(dResult['ANG'])*math.pi/180),
                                               0)]
#           except KeyError:
#                print "%s doesn't exist" % dResult['SEC']
            for line9 in resultelines:
                binf.write(line9)

The code part in relation to dictionary definition is
def section_material_read(Shell_Section_dic,Frame_Section_dic,Material_dic):
   Shell_Section_dic = {}
   Frame_Section_dic = {}
   Material_dic = {}
   Ex_Material_rec = False
   Ex_Frame_Section_rec = False
   Ex_Shell_Section_rec = False   ##  indicates if previous rec starts with "NAME="
   fp = PrivoxyWindowOpen("LBP_tenfloor.s2k", "r")
   for one_rec in fp:
      if 'NAME' in one_rec and 'MAT' in one_rec and 'TYPE' in one_rec:
            Shell_Section_dic, key = new_rec_list(one_rec, Shell_Section_dic)
            Ex_Shell_Section_rec = True
       
      else:
         if Ex_Shell_Section_rec:   ## only if previous rec was a "NAME=" rec
            Shell_Section_dic = append_rec_list(one_rec, Shell_Section_dic, key)
         Ex_Shell_Section_rec = False

      if 'NAME' in one_rec and 'MAT' in one_rec and 'TYPE' not in one_rec:
            Frame_Section_dic, key = new_rec_list(one_rec, Frame_Section_dic)
            Ex_Frame_Section_rec = True
       
      else:
         if Ex_Frame_Section_rec:   ## only if previous rec was a "NAME=" rec
            Frame_Section_dic = append_rec_list(one_rec, Frame_Section_dic, key)
         Ex_Frame_Section_rec = False   
         
      if 'NAME' in one_rec and 'IDES' in one_rec:
            Material_dic, key = …
jice 53 Posting Whiz in Training

Hi, guys

Another update about my question.

I used the stupid code mentioned above to identify line numbers as
113961 and 114961.

How can I use these two line numbers to specify a While or For loop? I am just jumping from a hole into another one. haha.

Ning

Why do you want to reloop on some part of you file instead of process it the first time.

jice 53 Posting Whiz in Training

Hi,

I used a stupid code below

i=0
for line99 in alllines:
    i=i+1
    if "LOAD" in line99:
        print "Line number is", i
        break

to achieve line number.

Any better code? Thanks.

ning

You can do (here, i imagine that you did something like alllines = a_file.readlines() ):

for i, line99 in enumerate(file("/path/to/infile")):
    if "LOAD" in line99:
        print "Line number is", i+1
        break
jice 53 Posting Whiz in Training

I thought of your problem this WE and wrote a solution.
I see other people have answered but I post mine as it is written anyway. It will give you another way to solve your problem in the same idea i gave to your other post.

lines=["1 J=2,7183 SEC=CON450X450 NSEG=2 ANG=0",
       "56 J=7224,164 SEC=CON450X450 NSEG=2 ANG=0"]
targetLine="*element,type=b31,elset=%s%s"
tLines=[]  # to store the modified target lines
for line in lines:
    resultDic={} # We will store the elements of the line in a dictionary
                  # like this {'id':'1', 'J':'2,7183', 'SEC':'CON450X450'...}
    splittedLine=line.split() # split the line using space
    for element in splittedLine:
        keyValue=element.split("=") # split the element using =
        if len(keyValue)==2:
            resultDic[keyValue[0]]=keyValue[1] # store the element in the
                                # dictionnary this way {"SEC":"CON450X450"}
        elif len(keyValue)==1:
            resultDic['id']=keyValue[0]
    tLines.append(targetLine % (resultDic['SEC'], resultDic['id']))

print "\n".join(tLines)
jice 53 Posting Whiz in Training

I changed the resline as suggested but everything works fine here.
What error have you got ?

jice 53 Posting Whiz in Training
import math
# First of all, Frame_Section should contain the following. Otherwise, you'll have
# to seach for your elements in the lists
# for elt in list:
#     if elt[0]='MAT':
#         result=elt[1]
# This way is far better
Frame_Section={'CON450X450': {'MAT':'CONC2', 'SH':'R', 'T':'.45,.45'},
        'B400': {'MAT':'CONC2', 'SH':'R', 'T':'.16,.4'},
        'FSEC1': {'MAT':'CON3', 'SH':'P', 'T':'.3048'},
        'B400H': {'MAT':'CONC2', 'SH':'R', 'T':'.16,.4'},
        'B200': {'MAT':'CONC2', 'SH':'R', 'T':'.16,.2'},
        'B300': {'MAT':'CONC2', 'SH':'R', 'T':'.16,.3'}}

resline="56 J=7224,164 SEC=CON450X450 ANG=45"
targetlines=["*beam section,section=R, elset=%s,material=%s",
             "%s",
             "%f, %f"]
dResult={}
# Store your resline elements in a dictionary
# 1st we split using the spaces
for elt in resline.split():
    keyValue=elt.split("=") # We separate the key from the value 
                            # and store them in a tempo list
    if len(keyValue)==2:
        dResult[keyValue[0]]=keyValue[1]
try:
    mat=Frame_Section[dResult['SEC']]['MAT'] # we get the MAT value
    # And the T values
    T=Frame_Section[dResult['SEC']]['T'].replace(".","0.") # To be simple,
                        # I do as if your floats always begin with a "." (less than 1)
    resultlines=[targetlines[0] % (dResult['SEC'], mat),
                 targetlines[1] % T,
                 targetlines[2] % (math.sin(float(dResult['ANG'])*math.pi/180), math.cos(float(dResult['ANG'])*math.pi/180))]
except KeyError:
    print "%s doesn't exist" % dResult['SEC']

for line in resultlines:
    print line
jice 53 Posting Whiz in Training

name = caffé
print name

Don't you mean :
name="caffé"

jice 53 Posting Whiz in Training

Here is a way to store your result in a list.

data = open ("files/" + data + ".txt", 'r')
file_list=[]
for line in data:
    print line
    file_list.append(line[34:38])

Just one point :
instead of "line[34:38]" which is dangerous in this kind of csv files, you can use :

file_list.append(line.split(",")[5][0:2])

This splits your line in a list, using "," as the splitting marker, takes the 5th element and takes the 2 first characters.
You can even do

file_list.append(line.split(",")[5].split(".")[0])

But if you have some more complex processes to do, yuou should have a look at the csv module...

jice 53 Posting Whiz in Training

I am programming a folder synchronizer for my first python project.
(I want to get it finished before school starts in about 2 months. heh heh)
Anyway, up till now my synchronizer will only copy file from one folder to another.
I want it to be able to copy entire sub folders but I don't know how to list the sub folders of a given folder using python code.
That's my QUESTION:
how do i list the sub folders of a directory?

Use the os.walk or the os.path.walk function (prefer the first one as this one is removed from python 3.0)

jice 53 Posting Whiz in Training

Firstly thankyou very much for getting back to me and I have took your suggestions on board. I think I'm closer now but when I run my program the disks still overlap. I'm not sure what I'm doing wrong.
Here is the loop I'm using now to move the disks.

while (nstep<1000):
    p = choice(array)  	#CHOOSE NUMBER OF STEPS 
    pnewx=p.x + (random() -0.5) #Generate a step in x	
    pnewy=p.y + (random() -0.5) #Generate a step in y	
    nstep=nstep+1
    for j in array: # any particle other than p
        distance=mag(vector(pnewx,pnewy)-j.pos) #distance between p and another particle
		
            if (distance>2*r):#if particles do not overlap then accept new values for co-ordinates
                p.x=pnewx
                p.y=pnewy
            else:
                reject=reject+1 #if they do overlap, do not accept new values, count how many times rejected

I think you have an indent problem : the if block isn't the same level as the distance=... line (but you should have an error here).
And another thing : i don't know what your p=choice(array) line does...
But i don't know if that remarks can solve anything as i can't test right now :-/

jice 53 Posting Whiz in Training

to know the index of a list element in a for loop you can try:

for i, element in enumerate(['a', 'b', 'c', 'd']):
    print i, element

# Result
0 a
1 b
2 c
3 d
jice 53 Posting Whiz in Training

As long as there is no comma in your individual data elements, you can use function join() and replace() in this manner:

q = ['23', 'CL', '006', '2004', 'DBA8ORPU', '41', '8Y', '0', 'S0111P', '2']

s = ",".join(q).replace(",", " ")

print(s)

"""
my result -->
23 CL 006 2004 DBA8ORPU 41 8Y 0 S0111P 2
"""

And why not directly :

s = " ".join(q)

print(s)

"""
my result -->
23 CL 006 2004 DBA8ORPU 41 8Y 0 S0111P 2
"""
jice 53 Posting Whiz in Training

To read and write dbf files, try the dbfpy module :
http://www.fiby.at/dbfpy/

A snippet example :
http://code.activestate.com/recipes/362715/

jice 53 Posting Whiz in Training
jice 53 Posting Whiz in Training

For line count, it is very easy (this is to be put after your own code) :

f = open ('out.txt', 'w')
for i, l in enumerate(file('site.txt', 'r')):
    if i > 10:
        f.write(l)

To delete part of the text, you can use regexp (this example erase the body part) :

import re
pat=re.compile("<body.*</body>", re.DOTALL) # re.DOTALL is to include \n
f = open ('out2.txt', 'w')
f.write(pat.sub("", text_file_read))
f.close()

You can also get the content of the part this way (have a look at the re module)

You can also parse your file but if you don't have any condition on the content to erase a part, it may be simpler to do this this way :)

To parse html files, you can use the HTMLParser module
For xml or xhtml files, you can use xml.sax or xml.dom modules

jice 53 Posting Whiz in Training

I think the error is here (and griboullis solution corrects it)

file=open("dinesh.csv") #prepare a csv file for our example

Here you open the file (in read only mode - the default value)

testWriter = csv.writer(open('dinesh.csv', 'w'), delimiter=' ',

And here, you reopen it when it is not closed... Not good habit ;)

jice 53 Posting Whiz in Training

With XnView (or any other software that provide this functionality)

If you want to do it with python, I suggest PIL :
http://www.pythonware.com/products/pil/
You should have a look at this :
http://www.pythonware.com/library/pil/handbook/pilconvert.htm

jice 53 Posting Whiz in Training

message = 'invalid mode: w'

try 'wb'

jice 53 Posting Whiz in Training

Why don't you use the second parameter of the seek function ?

From http://docs.python.org/library/stdtypes.html#file-objects :

file.seek(offset[, whence])¶

Set the file’s current position, like stdio‘s fseek. The whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.SEEK_CUR or 1 (seek relative to the current position) and os.SEEK_END or 2 (seek relative to the file’s end). There is no return value.

For example, f.seek(2, os.SEEK_CUR) advances the position by two and f.seek(-3, os.SEEK_END) sets the position to the third to last.

Note that if the file is opened for appending (mode 'a' or 'a+'), any seek() operations will be undone at the next write. If the file is only opened for writing in append mode (mode 'a'), this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+'). If the file is opened in text mode (without 'b'), only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.

Note that not all file objects are seekable.

Changed in version 2.6: Passing float values as offset has been deprecated.

jice 53 Posting Whiz in Training

You can use the tkFileDialog module
http://epydoc.sourceforge.net/stdlib/tkFileDialog-module.html
Example :

# -*- coding: iso-8859-1 -*-
import tkFileDialog
from Tkinter import *

class openDialog(Frame):
    def __init__(self, master=None):
        self.root=master
        self.createWidgets()

    def createWidgets(self):
        """ Create widgets
        """
        self.fFrame = Frame(self.root)

        self.svDir = StringVar()
        self.eDir  = Entry(self.fFrame, width=70, textvariable=self.svDir)
        self.eDir.pack()

        self.bSelDir = Button(self.fFrame, text="askdir")
        self.bSelDir["command"] =  self.getDir
        self.bSelDir.pack()

        self.fFrame.pack()

    def getDir(self):
        self.dir=tkFileDialog.askdirectory()
        self.svDir.set(self.dir)


if __name__ == "__main__":
    root=Tk()
    od = openDialog(root)
    root.mainloop()
jice 53 Posting Whiz in Training

You should use "*?" instead of "*" : * will take the longest string that match the pattern while *? will take the shortest.
p=re.compile(r'\b(href="(.*?)"){1}\b')

jice 53 Posting Whiz in Training

Do you use W$ or Linux ?
Where did you install the mySqlDb module ?
Is it in your site-package directory ?
Can you see this directory in your sys.path (in Idle : "File>path Browser")