jice 53 Posting Whiz in Training

Maybe you're right... I didn't look at that very much but you have some

while True:
    ...
    while True:
        ...

That i don't like very much... But in this case, i maybe wrong.
Anyway, vegaseat seems to know about threading and I don't so you'd better listen to him.

jice 53 Posting Whiz in Training

I don't have time to test extensively your code but i'd begin by looking at loops.
I've seen a couple of while True...
How long do you stay in these loops ?
You should test and locate precisely where your program lose time.

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

a fourth :

import re
st = "abcd123"
rdigit=re.compile("\d")
print rdigit.findall(st)

Which can be onelined :

import re
print re.compile("\d").findall("abcd123")
jice 53 Posting Whiz in Training
outfile = 'OUTPUT'
output = open(outfile, 'w')

for line in open('DATA'): # You don't need to open the file and load it in a list (bad for memory)
    linelist = line.strip().split() # Strip will remove trailing spaces and '\n'
    if linelist[1][4:6]=='MG' and linelist[1][-2:] not in ['RE', 'RD']:
        output.write(line)
jice 53 Posting Whiz in Training

I think this one is better...

import re
testStrings=[ "POST at the start without the other word", "GET at the start without the other word", "GET first\nthen POST and more", "POST first\nthen GET and more"]
splitter = re.compile('(POST|GET)')
for s in testStrings:
    splittedString=splitter.split(s)[ 1:]
    print [ splittedString[i]+splittedString[ i+1] for i in range(0,len(splittedString),2)]

But you can even do

import re
teststrings=["POST at the start without the other word", "GET at the start without the other word", "GET first\nthen POST and more", "POST first\nthen GET and more"]
print [(lambda splittedstring: [splittedstring[i]+splittedstring[i+1] for i in range(0,len(splittedstring),2)])(re.compile('(POST|GET)').split(s)[1:]) for s in teststrings]

which is less readable.
You have a one liner if you don't use the intermediate variable teststrings ;-)

import re
print [(lambda splittedstring: [splittedstring[i]+splittedstring[i+1] for i in range(0,len(splittedstring),2)])(re.compile('(POST|GET)').split(s)[1:]) for s in ["POST at the start without the other word", "GET at the start without the other word", "GET first\nthen POST and more", "POST first\nthen GET and more"]]
amadain commented: that is great. Thanks +1
jice 53 Posting Whiz in Training

[ ] is generaly used for indexing (see the list, tuple or dictionary chapters in the doc).

mylist=[ 1,2,3,4,5,6]
print mylist[ 3]

> 4

If you see strings like some kind of char tuple (immutable list), everything appears to be very simple as it works exactly the same.

Here is a completely stupid example :

mystring="qsdmlkiuranvdfkls"
for i, ch in enumerate(sorted(mystring)):
    print i, ch, mystring[i]
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

Hello,

c.execute("INSERT INTO a (first, last) VALUES (%s, %s), row")

Your "row" is inside the sql statement as a string !
You can do

c.execute("INSERT INTO a (first, last) VALUES (%s, %s)" % row)
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

Have you tried to call

EffectIllusion.illusionRace.get()

I don't know what StringCol is and how you should use it but it certainly provides something like get() or getValue()...

jice 53 Posting Whiz in Training

First of all, rewrite your code with correct indent.
This is very significant in python and your code is very strangely indented (i'm surprised this works...)
class effectIllusion shouldn't be indented,
nor def updateSimObjects(self):
if not mount0: and following is inconsistent...

darkbow commented: i think i wouldn't post here if indentation is the issue code blocks mess that up +0
jice 53 Posting Whiz in Training
##   and if you have an unusual series of numbers, use a list
iterate_list = [0.0, 0.2, 0.3, 0.5, 0.6]
for r in iterate_list:
    print r

To continue in this direction, you can use a list you construct the same time (called list comprehension)...
This is not very different of your solution, it simply shorten the code.

for y in [float(i)/10 for i in range(63)]:
    print y,
jice 53 Posting Whiz in Training

and you should use float instead of int

print float(miles_driven) / float(gallons_of_gas_used)
vegaseat commented: a good deduction +16
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

You're right... No need to re-invent the wheel.
The fact is that i've never used these functions (cmp, __cmp__ or whatever)... So I didn't think of it.
BUT, to save my honor and not commit seppuku, i'd add that the detailed function i wrote shows the principle of a __cmp__ function. You can test whatever you want (not only one field of each objet) and if __cmp__ returns -1, 0 and 1, you will be able to compare differents objects, sort() lists of them and so on. Simple, clean. Pythonic

Python is so clean and easy...
I'm writing some php code these days and I find it so heavy in comparison.

jice 53 Posting Whiz in Training

Beware of your indent... Very important in python

print 'one'
     print 'two'   # <== ERROR (one space too much)
    print 'three'

    if condition # < ERROR (missing :  )
    print "four" # < ERROR (missing indent)
jice 53 Posting Whiz in Training

Maybe is jlm699's solution simpler but i'll just put an example of what I said yesterday (I had no time to do it yesterday) as it is interesting anyway because it allows comparisons between objects in any situation (if objectA > objectB: )
note that __repr__ (as we are in special methods) allows to print the object the way you want...

class myobject:
    def __init__(self, c):
        self.c=c

    def __cmp__(self, alien):
        if self.c < alien.c:
            return -1
        elif self.c == alien.c:
            return 0
        else:
            return 1

    def __repr__(self):
        return str(self.c)

l=[]
for character in "akljdfliouerjslk":
    l.append(myobject(character))
print l
>> [a, k, l, j, d, f, l, i, o, u, e, r, j, s, l, k]
l.sort()
print l
>> [a, d, e, f, i, j, j, k, k, l, l, l, o, r, s, u]
jice 53 Posting Whiz in Training

Could you post some code or be more precise ?
Is this list made of objects from the same class ?
Maybe should you implement the __cmp__ OR __eq__, __ge__, __gt__, __le__, __lt__ and __ne__ special method in your object... That would allow comparisons between objects. and sort them

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

You can also do like this.
This avoids to load the whole file in memory...

for line in file("myfile.txt"):
    exec ("lst=%s" % line.strip())
    Prot='HPPHPPHHP'
    for i, coord in enumerate(lst):
        for elt in coord:
            print elt,
        print Prot[i]
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

I'd store the blocks in a list, looking for the pattern in each line and, if i find the pattern in one line, write the whole block out.

isBlockToWrite=False
pattern="COMMS_MESSAGE_SENT"
block=[]
outfile=file("log3.log","w")
for line in file("log2.log"):
    block.append(line)
    if line[:10] == "*" * 10:
        if isBlockToWrite:
            outfile.writelines(block)
        block=[]
        isBlockToWrite=False
    if pattern in line:
        isBlockToWrite=True
jice 53 Posting Whiz in Training

what is the precise error message ?
How did you install python ?
What is your OS ?

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

Ok.
You can delete cr by doing

lineA=lines[lpa].strip()
lineB=lines[lpb].strip()

For the end of your code, i think you can do the calculation by yourself :-)

BTW, i saw a mistake in my code :

for line in open('dicoFile.txt'): # I don't know why i have put a comment here
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

I post my answer here too (i did it first on your other thread)
you've got an easy way of doing this :

datas="""[(0,1),(1,1),(2,1),(2,2),(1,2),(0,3),(-1,4),(-2,4),(-1,5)]
[(0,1),(1,1),(2,1),(2,2),(1,2),(0,3),(-1,4),(-2,4),(-1,5)]
[(0,1),(1,1),(2,1),(2,2),(1,2),(0,3),(-1,4),(-2,4),(-1,5)]""".split('\n')
for data in datas:
    exec ("lst=%s" % data)
    Prot='HPPHPPHHP'
    for i, coord in enumerate(lst):
        for elt in coord:
            print elt,
        print Prot[i]

This is to be adapted for your exact need

jice 53 Posting Whiz in Training

you've got an easy way of doing this :

datas="""[(0,1),(1,1),(2,1),(2,2),(1,2),(0,3),(-1,4),(-2,4),(-1,5)]
[(0,1),(1,1),(2,1),(2,2),(1,2),(0,3),(-1,4),(-2,4),(-1,5)]
[(0,1),(1,1),(2,1),(2,2),(1,2),(0,3),(-1,4),(-2,4),(-1,5)]""".split('\n')
for data in datas:
    exec ("lst=%s" % data)
    Prot='HPPHPPHHP'
    for i, coord in enumerate(lst):
        for elt in coord:
            print elt,
        print Prot[i]

This is to be adapted for your exact need

jice 53 Posting Whiz in Training

Here are somme comments on what you ask.
This is not a working program but gives you functions you can use for the different steps using your way.
I don't understand everything you are doing and this seems very complicated to me. Very old style to deal with files.
Python offers tools that ease this kind of jobs very much. I propose you a working code after yours. It could be more efficient but would be less readable by using list comprehension so i wrote it this way.

#otigDict.txt   original File
#newDict.txt    new dictionary
lif = 1        # Lines_in_File
lpp = 1        # Lines per page, around 72
pc  = 1        # Pages completed
lpa = 0        # Line pointer a >> list first element is indexed 0
lpb = lpa + lpp # Line pointer b


#Open text files , the original to read the other to append
originalFile=open(otigDict,'r')
newDictionnary=open(newDict,'w')
#Calc. Lines in origDict.txt  = lif
# > for this, you have to load the whole file
lines=originalFile.readlines() # load the file in a list
nbLines=len(lines) # length of the list
#Take lines per page from user  = lpp (default = 72)
lpp=input("number of lines") # ask for the number of lines
if lpp=='':
    lpp=72
#
#					Q
#
#Read line  and delete cr = n (using lpa)
# > I don't understant what you mean with cr=n
lineA=lines[lpa] # read the line number lpa
#
#Read line = m (using lpb)
lineB = lines[lpb] …
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

Could you post an extract of the input file and an example of what you would like in the output one...

jice 53 Posting Whiz in Training

Just translate what you think :

f = open('testread.txt')
f1 = open('testread1.txt', 'a')
doIHaveToCopyTheLine=False
for line in f.readlines():
  if 'this is the line i want to search' in line:
    doIHaveToCopyTheLine=True
  if doIHaveToCopyTheLine:
    f1.write(line)
f1.close()
f.close()
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

Well, originally I was going to use function parameters to set the variables (i.e. testfunc(x, y, z) ) with the function and use the return, but those variables were hard to handle and weren't very flexible. Thanks for the idea though.

Sorry, but I can't understand what is hard to handle and not flexible...
I think exactly the opposite. Especially in python where you have *args and **args to have non fixed number of arguments. And you can return lists or dictionnaries...

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 ?