jice 53 Posting Whiz in Training

I don't think so : zip.write waits for a file NAME and you pass a file OBJECT.
I think this may be done by using the second argument of zip.write :

zip.write(filename, arcname=None, compress_type=None)
# filename = the file you want to archive
# arcname the name you give to the file in the archive (if None, it will be filename)
# compress_type = zipfile.ZIP_STORED or zipfile.ZIP_DEFLATED)
jice 53 Posting Whiz in Training

But one quick point is that if the letter is not standard, weight is tested but not yet defined (this is the translation of your error message)
Why do you test the size to allow the input of the weight : you ask the same question in both case. Don't test size.

jice 53 Posting Whiz in Training

So please, go on, repost your code with appropriate tags around it

jice 53 Posting Whiz in Training

How does this determine the row # of FCITC?

Here :

if "FCITC" in line:
        noline+=1

The code seems to set No line to 1. Is this saying that the FCITC is located at line 1 and that no line +=1 would be the following line where the values are located? Is this the same as noline==2?

The idea is to say :
when i see a line with FCITC in it, i increase the number (i named it noline but it may not be the best name... You can choose noLineRelativelyToTheHeaderLine ;-) )
If this number is 1, i load fcitc and limit constraint in variables and i increase the number.
If this number is 2, i load the Contingency description in another variable (i take the whole line and strip it as there is nothing else on this line) and set the number to 0 so that every other line is ignored until FCITC is found again.

d5e5 commented: Good start. It brought me closer to feeling I understood what the OP wants to do. +0
jice 53 Posting Whiz in Training

Are the fields separated with tabs, are their length fixed
I'd say fixed length
First (FCITC) is before 9th character
Limiting constraint is from 29th to 79 th
Contingency description is from 80th to 137th on the second line.
Is this ok ?
I'd do something like this

noline=0
for line in open("fcitc.txt"):
    if noline==1:
        fcitc=line[:9].strip()
        limConst=line[29:79].strip()
        noline+=1
    elif noline==2:
        contDesc=line.strip()
        print fcitc
        print limConst
        print contDesc
        noline=0
    if "FCITC" in line:
        noline+=1
jice 53 Posting Whiz in Training

My question is :
How do you recognise the elements you want to keep :
Why is this in red and black

#
FCITC TDF LODF <--------- Limiting constraint ---------> <--------- Contingency description ---------> Ncon PreShift Rating PTDF IntBase FnlBase
#
-626.4 -0.04873 0.30911 6106 I-STATE 230 6104 TENOROC 230 1 C: 7890

And why is this one not
If you can tell us the elements that show which part is to be selected, then you'll nearly have the answer...
#
<--------- Limiting constraint ---------> <--------- Contingency description ---------> Ncon PreShift Rating PTDF IntBase FnlBase
#
-443.2 -0.03919 -0.19893 6106 I-STATE 230 6104 TENOROC 230 1 C:9100-9120D 446 -454.4 -437.0 -0.02746 -377.1 -365.0
#
Open 9100 RECKER 230 9120 SELOSE 230 1

jice 53 Posting Whiz in Training

I can't copy the text to test...
Is this to be a html file ? Are the <br /> tags or are they supposed to show CR.
Your BBCodes don't work...
How can you select one line if all your file seems to be on an unique line ?

jice 53 Posting Whiz in Training

Vegaseat forgot a little point

# This script will determine the size if the gwarchive directories 
# in everyone's home folder

import os

folder_size = 0

for username in open("L:\\dirl.txt"):
    folder = "L:\\" + username.strip('\n') + "\\gwarchiv" # <== remove the ending "\n"
    print folder
    for (path, dirs, files) in os.walk(folder):
        for name in files:
            filename = os.path.join(path, name)
            folder_size += os.path.getsize(filename)
        print "Archive = %0.1f MB" % (folder_size/(1024*1024.0))
vegaseat commented: thanks, I didn't test my code +15
jice 53 Posting Whiz in Training

Hi
Thanks folks for your replies.
Testing the general format shown below returns a character and not the complete line

lpa=1
text_file = open("English101.txt", "r")
print text_file.readline()[lpa]
text_file.close()

What I am trying to achieve is that a complete line of text is returned, from a text file that has 600 lines or so. Maybe I am looking at the wrong instruction

readline() reads the next line. So, readline()[nb] takes the nbth character of the next line.
You can't read the nth line of a file that way. You have to read line by line TILL the nth line or read the whole file in a list (like you did in linelist) and then

lpa=1
text_file = open("English101.txt", "r")
linelist=text_file.readlines() # I load the whole file in a list
text_file.close()
print linelist[lpa]
chico2009 commented: Thanks a very helpful comment +1
jice 53 Posting Whiz in Training

you can use a dictionary but it won't be wise to use the surname as the key instead use the position number. for the itemvalues you can use a list and you can append new values later if needed so basically you have a list in the dictionary.

It is not wise IF you are not absolutely sure that you won't have two guys with the same name. Otherwhise this is not a problem...
Having said that, you can use the position number as suggested which is about to be the same as using a list.
To be able to store as many datas as you want, concerning players, you can use a list of dictionary like this :

myPlayerList=[{"name":"Jones",
               "tackles":[5, 6],
               "somethingElse":["aValue", "anotherValue"]},
              {"name":"Smith",
               "tackles":[4, 2],
               "somethingElse":["aValue", "anotherValue"]}
             ]
# then you call a value like this
name=myPlayerList[1]["name"]
tackleNb2=myPlayerList[1]["tackles"][1]

Or, if you want to use the names as keys (considering what has been said about that) :

myPlayerDict={"Jones":{"tackles":[5, 6],
                      "somethingElse":["aValue", "anotherValue"]},
              "Smith":{"tackles":[4, 2],
                      "somethingElse":["aValue", "anotherValue"]}
             }
# then you call a value like this
listOfJonesTackles=myPlayerDict["Jones"]["tackles"]
smithTackleNb2=myPlayerDict["Smith"]["tackles"][1]
jice 53 Posting Whiz in Training

Input Temperature in Celcius in Main function in 1st.py file passed on as variable C.

so you call, in your Main function

def Main():
    C=int(input("°C ?"))
    F=twond.CelciusToFarenheit(C) # Here, the returned value is stored in F
        # But this F has nothing to do with any F you'll see in the second function (same name but different variables)
        # You'll see later...

Second function in file twond.py will convert that to Fahrenheit and store in variable F.

This is where you have to concentrate ;-)
The Main function doesn't care about where the second function (let's say CelciusToFarenheit) stores its intermediates values.
It only cares about what is returned

def CelciusToFarenheit(C):
    F=1,8C+32 # Main() won't see this F whatever you do
    return F # This will return the value to the calling function (here Main). It returns a Value.
        # It is called F here but it could be called anyway the result would be exactly the same

Now this should be passed back of to main function in 1st.py file.
So when i command print(F) in the main file, it prints the output in Fahrenheit. So now I can use this Fahrenheit and play with this variable.

Let's complete the Main function

def Main():
    C=int(input("°C ?"))
    F=twond.CelciusToFarenheit(C)
    print (F)
    # play with F as much as you want. As soon as the returned value is stored in a variable, it can be used.
    A=F*1.05
    print (A)
romes87 commented: Very helpful +1
jice 53 Posting Whiz in Training

My suggestion was this one. And the same the others made.
If you simply had added this line I suggested, your program would have worked. Without any other change.
Functions are to return values (one or more) and this is to be used.

first of all your function getdata should return the values you want :

def getdata(data):
    # the code you've already written
    return number, items
jice 53 Posting Whiz in Training

And what is the error ?

jice 53 Posting Whiz in Training

The only variables you can use in the calling program are the returned variables (you can use a intermediate variable in the function but you MUST return it to use it in the main program).

Except if you embed your second function in a class (which is the base of Object Programming :

#this is the file twond.py which splits the string s  and returns the splitted line
class twond:
    def second(self, s):
        self.splittedString=s.split()

Then in your 1st file, you can do

#this is the main file 1st.py which has a string stored in variable s and a GUI function that calls the function
#
from Tkinter import *
import twond


class App:
    def __init__(self,master):
        frame = Frame(master.title("New Title"))
        frame.pack()
        self.bt=Button(frame, text='click', command=self.first)
        self.bt.grid(row=1, column=0)
    #global L    
    def first(self):
        s = 'this is a string'
        t=twond.twond()
        t.second(str(s))  #this passes the variable s to the twond object second() method

        print(t.splittedString) 

root = Tk()
app = App(root)
root.mainloop()

In this example, this wouldn't be a very good design : it's not a good habit to access object attributes directly (better to define a setAttribute and a getAttribute in the twond object to manipulate the attribute).

Another thing you can look at in gui design is "callback" : you pass a function as a parameter to another function so that you can call the first function from the second one... Very useful to avoid nested imports.
I won't develop this more here but you can google "callback" and …

jice 53 Posting Whiz in Training

Ok, I put the whole code down :
Here is what I was saying :
I have written 2 files
1st.py and twond.py

#this is the main file 1st.py which has a string stored in variable s and a GUI function that calls the function
#
from Tkinter import *
import twond


class App:
    def __init__(self,master):
        frame = Frame(master.title("New Title"))
        frame.pack()
        self.bt=Button(frame, text='click', command=self.first)
        self.bt.grid(row=1, column=0)
    #global L    
    def first(self):
        s = 'this is a string'
        splittedString=twond.second(str(s))  #this passes the variable s to the function second() in the file twond.py

        print(splittedString) 

root = Tk()
app = App(root)
root.mainloop()
#this is the file twond.py which splits the string s  and returns the splitted line
# import string : deprecated. Not to be used any more

def second(s):
    return s.split()

When I press the button, my console is displaying :

> ['this', 'is', 'a', 'string']

So, I don't understand what is going wrong with this. I certainly don't have any AttributeError.

jice 53 Posting Whiz in Training

Why don't you def your function like

def second(s):
    str = string.split(s)
    return str

then you can print it like

print str(second(string))

I don't understand the problem : if you do like this, you can call the function from the other file doing :
print str(twond.second(string))
and it will work, no ?

jice 53 Posting Whiz in Training

The use of global variables is a BAD IDEA.

jice 53 Posting Whiz in Training

I'm afraid not :
in html pages, there is no way to know where the address is : no special tag or whatever. So you have to look at the sites you want to process and look how you can identify the address.
I'd even say that sometimes, it may be impossible (for example, if you hadn't "Permanent Address", the example you gave me would have been very difficult to process)

jice 53 Posting Whiz in Training

It's easier with a clear demand ;-)...
Here, you don't have any easy pattern to isolate the adress.
You'll need to look at the source of the html page to see the elements that can help you to identify the adress.
Here, for example, i'd look for "Permanent Address" and get the text from the following line to the following </tr> (between these two, you've got all the adress).
Then you just have to clean the text by removing all the tags.

import re
infile="personal-details.htm"
patternIN="Permanent Address" # Where to begin to keep the text
patternOUT="</tr>"  # Where to end to keep the text (after the begining)
keepText=False  # Do we keep the text ?
address=""      # We init the address
# Now, we read the file to keep the text
for line in open(infile):
    if keepText:
        address+=line.strip()  # We store the line, stripping the \n
        if patternOUT in line: # Next line won't be kept any more
            keepText=False
    if patternIN in line: # Starting from next line, we keep the text
        keepText=True

# Now, it's time to clean all this
rTags=re.compile("<.*?>") # the regexp to recognise any tag
address=rTags.sub(":", address) # we replace the tags with ":" (I could have chosen anything else,
                # especially if there is some ":" in the address
rSep=re.compile(":+") # Now, we replace any number of ":" with a \n
address=rSep.sub("\n", address)
print address
jice 53 Posting Whiz in Training

this may be working.

import re
datas=open("file.html").read()

expr=re.compile("<adress>(.*?)</adress>")
for match in expr.findall(datas):
    print match
jice 53 Posting Whiz in Training

first of all your function getdata should return the values you want :

def getdata(data):
    # the code you've already written
    return number, items
jice 53 Posting Whiz in Training

I would do

if x in [1,2]:
jice 53 Posting Whiz in Training

note :
10 power 3 = 10 * 10 * 10
5 power 6 = 5 * 5 * 5 * 5 * 5 * 5

jice 53 Posting Whiz in Training

Just to help you to understand what you have to do :
a is a power of b if it is divisible by b and a/b is a power of b :
a is power b => a/b is power of b :
example :
1000 is power of 10 ?
1000 / 10 = 100
is 100 a power of 10 ?
100 / 10 = 10 which is, obviously, a power of 10 so 100 is a power of 10, so 1000 is a power of 10.

Is 3 a power of 4 ?
3 / 4 = 0.75 which is not a power of 4.

jice 53 Posting Whiz in Training
def testfunc():
    global c
    c = "test"

testfunc()
c1 = c
del c
print (c1)
input ()

My question is : why don't you do

def testfunc():
    return "test"

c1 = testfunc()
print (c1)

I totally agree with what is said : globals should never be used except if you really know what you do. It's very dangerous.
I don't see that it makes things easier (maybe when you write your code for first time). In your example, where is the need of a global ?

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

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

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

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
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 ?