woooee 814 Nearly a Posting Maven

Duplicate post removed.

woooee 814 Nearly a Posting Maven

In addition to/instead of printing the file name, send the file name to another function at that point and that function can do whatever you want with that file.

woooee 814 Nearly a Posting Maven

The error is in this line
print (edgelist1[1],edgelist1[nextrow][1])
when you get to the last record, nextrow points beyond the end, so you want to use
for i in range (0,listmax-1):
since there is nothing to compare the last record to. Alternatively, you can use
for i in range (1, listmax):
and compare this record to the previous record. Also you want to be sure that the records are in numerical order, otherwise sort them first.

Second, you do not need the while loop, as the for loop goes through all of the records, and you could get duplicate output, one from the while loop, and one from the for loop. You can then print the index value from the for loop which is also the record number (or index+1 if you want the first record to be one instead of zero). Finally, it is bad practice to use "i", "l", or "o" as single digit variable names as they can look like numbers.

for x in range (0,listmax-1):
    nextrow=x+1
    if edgelist1[x][0]==edgelist1[nextrow][0]:
       ##   how this print statement should be formated depends on
       ##   the Python version you are using
       print ("rec # %d  %s  %s" % (x+1, edgelist1[x][1], edgelist1[nextrow][1]))
woooee 814 Nearly a Posting Maven

so i wan(t to) use endswith Main Page.txt to search

Post the code that reads the directory and your usage of endswith. I don't see a problem here, i.e. read the directory and go through the list to see if the file name ends with whatever.

woooee 814 Nearly a Posting Maven
data=line.split()
maxval=data[0]

because you are using strings instead of integers. So converting to an integer would look like this.

file_in = open( 'cont.dat',"r")
data_in=file_in.readlines()
file_in.close()
coloumn=[]
for line in data_in:
    data=line.split()
    ncoverage=len(data)

    ##   convert to integer
    maxval=int(data[0])

    maxid=0
    for j in xrange(0,ncoverage,1):

        ##   convert to integer
        if int(data[j])>= maxval:
            maxval=int(data[j])
    print maxval
woooee 814 Nearly a Posting Maven

Read the directory and then use os.stat to get file info. You will probably want to use one of st_atime, st_mtime, or st_ctime depending on which OS system you are on.

woooee 814 Nearly a Posting Maven

This type of thing generally used for creating a menu using a dictionary. An example of a menu using eval() to call the function:

def func_1():
   print "     func_1 test"
def func_2():
   print "     func_2 test"
def func_3():
   print "     func_3 test"
def func_4():
   print "     func_4 test"

##----------------------------------------------------------------
##   dictionary = list of function to call and menu choice to print
menu_d = { 1:['func_1()', '1)Load'], 
           2:['func_2()', '2)Save'], 
           3:['func_3()', '3)Add Phone Number'],
           4:['func_4()', '4)View Phone Number'],
           5:["", "5)Exit"]}
choice = 0
while choice != 5:
   print "\nSelect an Option\n"
   for j in range(1, 6):
      print menu_d[j][1]   ## print list's element #1 for key=j

   choice = int(raw_input( "Enter choice, 1-5 " ))
   if choice in menu_d:
      dict_list = menu_d[choice]
      eval(dict_list[0])
      ## eval(menu_d[choice][0])   will also work
print "\nend of program"
woooee 814 Nearly a Posting Maven

The problem may be in the code below. In the first case, if user_input == '', you are passing a file name with the corresponding directory(s). In the second case, "else", you are passing the directory only, that was input by the user. This type of problem is generally a bad path, so break the code into pieces by commenting what you don't want, and print the file and path name everywhere you use it.

if __name__ == "__main__":
    print os.getcwd()
    if user_input == '':
        for root, dir, files in os.walk(os.path.abspath(os.path.dirname(sys.argv[0]))):
            filelist = [ os.path.join(root,fi) for fi in files ]

        for track in filelist:
            rmtrcknum(track)

    else:
        rmtrcknum(user_input)

You perhaps want something like this but I am not sure what user_input or sys.argv is so you may have to adjust.

if __name__ == "__main__":
    print os.getcwd()
    path_name =user_input
    if user_input == '':
        ## print sys.argv and see what it prints
        path_name = sys.argv[1]   ## you want [1]

    for root, dir, files in os.walk(os.path.abspath(os.path.dirname(path_name))):
        filelist = [ os.path.join(root,fi) for fi in files ]

    for track in filelist:
        rmtrcknum(track)
woooee 814 Nearly a Posting Maven

when I try to remove a single appearance of a number from a square, the number is removed from all the squares in the grid

Generally that means that you are not declaring a list of independent lists but a list of references to the same list. Show us how you are creating "grid", and/or loop through and print id(this_sub_list) and see if the addresses are the same.

##---  This declares a 3X5 list and prints the memory address
grid = []
for j in range(0, 3):
   grid.append([ [] for x in range(5) ])
print grid

for j in range(0, 3):
   for k in range(0, 5):
      print id(grid[j][k])

Edit: Based on shadwickman's post, you probably did something like

##--- declare a 1X3 list for testing
grid = []
sub = []
for j in range(0, 3):
   grid.append(sub)
print grid

for j in range(0, 3):
   print id(grid[j])     ## they are all the same
woooee 814 Nearly a Posting Maven

A quick look says that classes/__init__() requires parens, i.e.

g.QuitButtonBB()

If that does not solve the problem, then post back. And "(code = python)" evidently does not work. Use the plain old "(code)" instead.

woooee 814 Nearly a Posting Maven

Having one list like L1 =
need to do pop operation and assign value like,
z1 = L1.pop()
z2 = L2.pop()
z3 = L3.pop()

In Python you do not have to reassign the value. Use the list values, unless you reassign for some other reason.

list_1 = ['a', 'b', 'c', 2, [3, 4, 5] ]
print list_1[-1]
##
el = len(list_1)
while el > 0:
   el -= 1
   print list_1[el], type(list_1[el])
woooee 814 Nearly a Posting Maven

by putting the cursor to the end of the
for c in chartNames:
and pressing an enter I get compile error.

"I get a compile error" is too vague for anyone to figure out. It is probably that the blank line is not indented at the same level as the other lines and your editor does not like that (which is overly picky, but at the discretion of whoever wrote the editor), but as I said it is impossible to decipher without the line number of the error and what it is. Use try/except, especially when testing.

try:
    for c in chartNames:
        chartUrl = baseChartUrl+c
        hd = extractChart(chartUrl)
 
        writeChart(hd,c)
 
        for key in hd:
            if key in chart:
                chart[key].append(c)
            else:
                chart[key] = [c]
except:
    import traceback
    traceback.print_exc()
    raise
woooee 814 Nearly a Posting Maven

And if you want to follow along with your first idea, you have to return the total if you want to access it outside the function.

def test(l):
    total = 0
    number = input("Number: ")
    for count in range(1, number+1):
        value = (count) * 20
        print "value =", value
        total += value
    print "The total =", total
    return total

## for what it's worth, since you multiply by 20, you can just add 
## up the range and multiply that by 20 as well.
woooee 814 Nearly a Posting Maven

And the following works fine for me, so it may have something to do with the regex as stated above. Try running the code with the "re.sub" line commented and see if that makes a difference.

s = u'La Pe\xf1a'         
print s.encode('latin-1') 

x = u"Rash\xf4mon"
print x.encode('iso-8859-1') 

##-----prints-----
La Peña                                                                 
Rashômon
woooee 814 Nearly a Posting Maven

EDIT: it's not the print statement that is failing.
Sometimes the except statement runs for no apparent reason even after the self.cursor.execute completes

Which means it is the print statement that is causing the error. Break it up to see which part is the problem (which should make it obvious since you are only printing one variable). Without a proper error message there is no way to debug, so note the addition of the traceback.

def db_insert(self,query_string,*params):
        try:
            self.cursor.execute(query_string, params)
            print ("Inserted into: "),
            print(self.database) 
        except:
            import traceback
            traceback.print_exc()
            raise
            print("!!!!WARNING!!!! Insertion into "+self.database+" failed.\n")
woooee 814 Nearly a Posting Maven

Something like

item.replace('/', '') for list[1]

Instead of scanning the whole list, it looks specifically at the line which I know will contain the backslash.

What happened when you tried it?

woooee 814 Nearly a Posting Maven

Because of the slash it gets a little tricky. I have found using split to be more reliable.

name_list = ['adam', 'bill', 'jon/juan']
list_2 = []
for this_name in name_list:
      substrs = this_name.split("/")
      each_name = "".join(substrs)
      print each_name
      list_2.append(each_name)
print "list_2 =", list_2
#
##--------------  or ------------------------------
list_3 = []
for each_name in name_list:
      list_3.append("".join(each_name.split("/")))
print "list_3 =", list_3
woooee 814 Nearly a Posting Maven

You can do this two different ways.

items = {'sword':['sword', 3, 15],
             'axe':['axe', 5, 25],
             'bow and arrow':['bow and arrow', 4, 20]}

##---- the easiest to understand
for key in items:
   print "key =", key
   weapon_list = items[key]
   print "\tweapon_list =", weapon_list
   print "\tprice =", weapon_list[1]
   print "\tdamage =", weapon_list[2]
   
##--- the way you tried to do it
for key in items:
   print items[key][0]
   print '\tprice:', items[key][1]
   print '\tdamage:', items[key][2]
Ene Uran commented: good explanation +7
woooee 814 Nearly a Posting Maven

6.1230317691118863e-17

Note the e-17. This is a very small number and the closest that floating point numbers can come (similiar to converting 1/3 to a base 10 decimal). See here http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate and http://www.lahey.com/float.htm You have to use sloppy logic with floating point numbers

print "%10.7f" % ( math.cos(90*math.pi/180)) or
x = math.cos(90*math.pi/180)
if x < .00000000001:
   print "x = zero"

For greater precision you have to use Python's Deciimal module http://www.python.org/doc/2.5.2/lib/module-decimal.html but add on the trig functions from here http://pypi.python.org/pypi/AJDecimalMathAdditions/0.2.0 Also take a look at NumPy http://wiki.python.org/moin/NumPy This is the Numeric/Scientific Wiki http://wiki.python.org/moin/NumericAndScientific

woooee 814 Nearly a Posting Maven

Section 1 in this online book has some beginning class examples. http://www.mindview.net/Books/TIPython

woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

To start, list_of_numbers is not a list of numbers but an integer. Or,
list_of_numbers = int (list_of_numbers)
will throw an error because you can not convert a list, and there would be no need for a while loop either. Most people who see
list_of_numbers = (input("Enter a list of numbers, (Enter -1 to stop): "))
would enter a list of numbers, i.e. 1,2,3

Your next step is to store each input number in a list. Then it becomes fairly simple; total the numbers in the list and calculate the average. For the max and min, you can either traverse the list and find the max and min, or test each number as it is input and store in variables if they are the largest or smallest so far.

woooee 814 Nearly a Posting Maven

This is one error. I don't have time to dig any further now, but if there are other problems, post back.

def make_bombs(self):
        bombs_created = 0
        while bombs_created < self.bombs:
                col = randint(1, self.columns)
                row = randint(1, self.rows)
                loc = (col, row)

                BombButton(loc)
                self.bomb_buttons.append(BombButton)

                ## the above 2 lines chould either be
                self.bomb_buttons.append(BombButton(loc))
                ## or
                this_button = BombButton(loc)
                self.bomb_buttons.append(this_button)

                bombs_created += 1

Also, add some print statements to each of the classes, so you know how far you get each time.

woooee 814 Nearly a Posting Maven

The problem is the @staticmethod decorator in both of your examples. Delete that line and the first program runs OK
[plus you only supply 'instance' once, i.e.
instance.do_stuff_with_var() ].
I have not tested the second program, but that would be the place to start. Since you only have one "do_stuff_with_variables" function in the first example, and only one "find_adjacent_cells" function, @staticmethod seems unnecessary anyway. Try either example without this and if it does not do what you want, post back.

woooee 814 Nearly a Posting Maven

Split the string on whitespace and check the first character of each word. You can use >= "A", <="Z"; or check that the ord of the character is within the capital letter range; or create a list of capital letters and use "if the first letter is in the list".

woooee 814 Nearly a Posting Maven

Use a dictionary, with port number as the key, pointing to a list of servers running on that port.

allports = list(set(total.keys()))
lines = total.values()

data_dict = {}
for port in allports:
    for line in lines:
        this_port = line[1]
        ## add key to dictionary if it doesn't exist, 
        ## pointing to an empty list
        if this_port not in data_dict:  
            data_dict[this_port] = []

        data_dict[this_port].append(line[0])

keys = data_dict.keys()
keys.sort()
print keys
woooee 814 Nearly a Posting Maven

That works just fine. Being paranoid, I like to supply defaults. Using a class works fine until it becomes too cumbersome or you want a better way of looking things up, then you move up to using an SqLite DB in memory.

class MyClass:
	def __init__(self, f=" ", r=[]):
		self.first = f
		self.rest = r

if __name__ == "__main__":
   list_of_classes = []
   list_of_classes.append(MyClass())
   list_of_classes.append(MyClass("x", ["a", "b"]))
   print "----->", list_of_classes[1].first
   print "----->", list_of_classes[0].rest
woooee 814 Nearly a Posting Maven

The key is these lines
MM=[]
print "start of loop", MM
If it is just overlaying the previous item, then this print should print the previous item. What exactly does the first line above do each time you cycle through the for loop?

Edit: try this instead

n=range(0,31)
x=[]
MM=[]
for x in n:
   print "\nreally at the start of loop", MM
   AL=5000.00
   MM=[]
   print "start of loop", MM
   MM_Income=12000.00
   MM_Cost=8000.00
   MM_Inc=800.00
   MM_Own=11
   MM_ROI=(MM_Income/(MM_Cost+(MM_Inc*x)+AL)*100)
   MM.append(MM_ROI)
   print "after appending", MM
   print (MM_ROI)

MML=zip(n,MM)
print (MML) 

print "x is", x, type(x)
woooee 814 Nearly a Posting Maven

Somestruct = Struct .new(:character, :characterArray)
structure = Somestruct.new(" ", [])

This is just a simple list or tuple in python. Try this

structure = []
Somestruct = (" ", [])
structure.append(Somestruct)
Somestruct = ("1", ["abc", "def"])
structure.append(Somestruct)
print structure

If you want more than that, then use a list of classes, with each class defining/declaring what you want.

woooee 814 Nearly a Posting Maven

Add 2 other print statements to see what is happening. Note that the statement
x=[]
does nothing since you redefine x in the next statement.

n=range(0,31)
x=[]
for x in n:
   AL=5000.00
   MM=[]
   print "start of loop", MM
   MM_Income=12000.00
   MM_Cost=8000.00
   MM_Inc=800.00
   MM_Own=11
   MM_ROI=(MM_Income/(MM_Cost+(MM_Inc*x)+AL)*100)
   MM.append(MM_ROI)
   print "after appending", MM
   print (MM_ROI)
   MML=zip(n,MM)
   print (MML)
woooee 814 Nearly a Posting Maven

Yes that should have been one to get the next value. A good example of why we don't use "i".

vegaseat commented: good example +12
woooee 814 Nearly a Posting Maven

You want to stop at the next to last item in the list, so "+1" will be the last item. Also, do not use "i", "l", or "o" as single letter variable names. They look too much like numbers.

list1 = [4,20,2,19,3254,234,21,03]

stop = len(list1) - 1
low = list1[0]
for x in range(0, stop):
   if list1[x] < list1[x+i]:
       print x, list1[x], list1[x+1]
   if list1[x+1] < low:
      low = list1[x+1]
print "lowest =", low
woooee 814 Nearly a Posting Maven

A google will yield a lot of hits. The python wiki is always a good place to start. http://wiki.python.org/moin/GuiProgramming

sneekula commented: good site +8
woooee 814 Nearly a Posting Maven

TypeError: String or Unicode type required

So this would probably work by converting to a string.

index = self.screen.InsertStringItem(sys.maxint, str(data[0]))
woooee 814 Nearly a Posting Maven
if row[i] == '':
			v = 0
                    else:
		        v= float(row[i])
                    self.csvData[i].append(v)

In this code, it could be the append statement that is taking the time since it is a large file. Store "i" and "v" in a dictionary until the end. After the loop is finished, instead of appending, it would probably be faster to loop through self.csvData, and append to a second list with the changes added. I don't know the internals of lists, but appending to the first list probably means that data has to be moved when something additional is inserted, which takes time. Writing to a second list, or file, just adds it on at the end. Also, using a dictionary would be even faster, or multiple lists with smaller amount of data per list. It would be simple to time this function, just two calls to datetime.datetime.now(), etc. to see if this is hanging the program.

As far as non-blocking goes, on Linux you can nice to a higher number (see man nice) which means it runs at a lower priority. Blocking would be more of an OS implementation, unless you are talking about blocking something in the same program.

Edit: What is self.csvData.append(v) and do you mean
self.csvData = v
and can you just write each line as it is encountered

for row in reader:
                for i in range(12):
                    output_row= []     ## empty list for each line
                    if row[i] == '':
			v = 0
                    else:
		        v= float(row[i])
                    output_row.append(v) …
woooee 814 Nearly a Posting Maven

[sarcastic] Damn, how many gigabytes is this code. Trim it down to one million lines of code so you don't have to zip it. [/sarcastic]

woooee 814 Nearly a Posting Maven

File "F:\My Projects\Python\PhoneBook.py\mainfile.pyw", line 79, in OnPopulate
index = self.screen.InsertStringItem(sys.maxint, data[0])

[(1, u'Steve', u'Giddy', u'0654743553'), (2, u'Majia', u'Ukonovic', u'65473032'), (3, u'Joseph', u'Ryanc', u'7663991109')]

If this list is "data" then data[0] is a tuple. If the first tuple is "data" then data[0] is an integer. Print data and type(data).

woooee 814 Nearly a Posting Maven

When comparing two strings you want to make sure they are the same length. They will never be equal if they are different lengths, so add a statement which prints if they are not equal,

log_fp=open('log.txt','r')
read_log=log_fp.read()
while choice!=read_log:
    if len(choice) != len(read_log):
        print "choice length", choice, len(choice), \
                "and read_log length", read_log, len(read_log)
    choice=random.choice(combos)
print choice
woooee 814 Nearly a Posting Maven

Tkinter's FileDialog is a easy way to select a file name. Double click to select a directory or file.

from Tkinter import *
from FileDialog import FileDialog

def GetFilename( dir = "" ):
    top = Tk()

    d = FileDialog( top )
    fname = d.go( dir )
    if fname == None :
        print "No file found", fname
        fname = "****"
    else :
        print "The file is %s" % (fname)

    return fname

##================================================================
if __name__ == '__main__':
    ret_filename = GetFilename( "/home/")
    print "filename returned is %s" % (ret_filename)
woooee 814 Nearly a Posting Maven

The aorkeys extract correctly,

Assuming that this means that the list aorkeys contains all of the numbers that you want to find, and that it is not a huge list, it is easiest to look for each key in the list.

h = open(redFile,'w')
g = open(orgFile,'r')

#Search each entry in file.lst, if an entry is for a desired object
#add it to the output file

for rec in g:
   for key in aorkeys: 
      if key in rec:
         h.write("%s\n" % (key))
g.close()
h.close()

This is simplier, but potentially more time consuming than finding the number on each individual line and looking it up.

woooee 814 Nearly a Posting Maven
This seems at odds with your analysis. Or am I missing something?

Python uses a list to store small numbers as that is more effecient so all small numbers point to the same object in the list which is why you get a True for a=1. The "is" operator though is for testing if it is the same object, and not equality. So
a=1
print a is 1
prints True because they both point to the same object. However, if you use a larger number, which is system dependent, but can be as small as 257, you will get a False for the same code. The point here is to use == for equality, as "is" will not give consisitent results. In fact, on my system I get different results with the same code run from the interactive prompt vs. running it in a .py file. From here http://docs.python.org/c-api/int.html

"The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object."

And for those who like to read http://svn.python.org/projects/python/trunk/Objects/intobject.c

"Integers are quite normal objects, to make object handling uniform.
(Using odd pointers to represent integers would save much space
but require extra checks for this special case throughout the code.)
Since a typical Python program spends much of its time allocating
and …

woooee 814 Nearly a Posting Maven

You maybe want "focus" or "geometry" depending on what you mean by "mouse position". You can find examples for both of them here http://infohost.nmt.edu/tcc/help/pubs/tkinter/

woooee 814 Nearly a Posting Maven

how can I achive mutliple matches from a line in single if statement like I need to ignore a line that starts with '<' and ends either with '>' or ' ; '

The simpliest way, without using and/or combinations, is to use an indicator which you set to True if found.

test_data = [ "keep this line>",
              "<ignore this line>",
              "<ignore this line also;" ]
              
ignore = False
for rec in test_data:
   rec = rec.strip()
   if rec.startswith("<"):
      if rec.endswith(">") or rec.endswith(";"):
         ignore = True
         
   if ignore:
      print "Ignore",
   else:
      print "OK",
   print rec
woooee 814 Nearly a Posting Maven

lsof will list all open files on the system and has many options for what is reported. See this page http://www.ibm.com/developerworks/aix/library/au-lsof.html

woooee 814 Nearly a Posting Maven

Use a list for the correct responses within some kind of while loop

exit = False
while not exit:
   #Limit the answer to a combination of r g b y o p
   colorCode = raw_input("Player 1 enter the secret code. No cheating player 2! ")
    if colorCode in ['r', 'g', 'b', 'y', 'o', 'p']:
       ## OK so ask next question
       #Limit the answer to numerical characters only. 
       # If not numerical, ask again.
       maxGuesses = raw_input("How many guesses do you want to give player 2? ")
       if maxGuesses.isdigit():
           H = Hints(int(maxGuesses), colorCode)   ## or whatever
           ##  exit loop
           exit = True
woooee 814 Nearly a Posting Maven

Try adding print statements to both functions. "None" means that no pattern match was found.

def find_name():
    folder = "C:/Users/Sam/Desktop"
    for filename in os.walk(folder).next()[2]:
        print "testing filename", filename
        if pattern.match(filename):
            print "find_name returning", filename
            return filename
 
def main():
    newname = str(duration) + ".txt"
    filename = find_name()
    print "filename returned is", filename
    ## comment the next line for now, until you get
    ## the program fixed
##    os.rename(filename, newname)

Then see the article here, especially the os.path.normpath() http://pythonconquerstheuniverse.blogspot.com/2008/06/python-gotcha-raw-strings-and.html (This question has been asked so many times that it seems no one will answer it anymore.)

woooee 814 Nearly a Posting Maven

Another idea. You can also split on the "AND" and then split on "|" removing the [-1] element.

test_input = "AND Category 07|Spec 01|ABC 01 AND Category 07|Spec 02|XYZ 02 AND Category 07|Spec 03|PQR 03 "
after_and_split = test_input.split("AND")
print after_and_split

new_str = ""
for str in after_and_split:
   after_line_split = str.split("|")
   ## length has to be > 1, otherwise nothing is left after removing -1
   if len(after_line_split) > 1:
      print "     after_line_split", after_line_split
      del after_line_split[-1]
      new_str += "AND" 
      new_str += "|".join(after_line_split) + " "
print new_str 

AND Category 07|Spec 01 AND Category 07|Spec 02 AND Category 07|Spec 03

Edit: I hope this isn't homework since it's too late now.

woooee 814 Nearly a Posting Maven

Please don't spam this site or someone will report you and you will be banned. Since the OP didn't say which toolkit or OS was involved, it is obvious that there is no way to recommend anything, hence MESHIKUMAR and mohankumar554 are the same and are spamming.

vegaseat commented: thnaks for the spam fight +12
woooee 814 Nearly a Posting Maven

This was the second entry from a Google for "python list write"
http://www.daniweb.com/forums/thread173615.html

and effbot is usually in search results. This explains writelines(), but writelines() does not insert a newline but is useful for transferring lists to a file.
http://effbot.org/zone/python-list.htm

slate commented: Straihgt to the point. +1
woooee 814 Nearly a Posting Maven

Double post deleted.