SEARCH YOUR SOLUTION HERE  

reading list of list to a file


i made a list of lists but i cant write it into a file. how do i get the
first string in a sublist
--
View this message in context: http://www.nabble.com/reading-list-o...p14239876.html
Sent from the Python - python-list mailing list archive at Nabble.com.

Posted On: Wednesday 7th of November 2012 01:20:51 PM Total Views:  298
View Complete with Replies




Related Messages:

RE: threading   (115 Views)
1. check out the Caveats for thread module: http://docs.python.org/lib/module-thread.html Threads interact strangely with interrupts: the KeyboardInterrupt exceptionwill be received by an arbitrary thread. (When the signal module is available, interrupts always go to the main thread.) i.e., all threads (including main) to catch interrupt exceptions, and propagate that information to other threads. 2. since there is no way to interrupt a sleep (not aware of any), sleep is not the choice. use something else like napping. I mean, take shorter intervals of sleep, check every thing is fine and go back to napping. if something is fishy - go catch it. hope that helps. Edwin -----Original Message----- From: python-list-bounces+edwin.madari=verizonwireless.com@python.org [mailtoython-list-bounces+edwin.madari=verizonwireless.com@python.org] On Behalf Of Rhamphoryncus Sent: Thursday, August 14, 2008 2:52 PM To: python-list@python.org Subject: Re: threading On Aug 14, 3:30am, "Mathieu Prevot" wrote: > 2008/8/13 Parimala : > > > > > , > > > I am using python2.5.1 version to run my test scripts. Iwant to use > > 'threading' module in my tests. As a startup program, I had run the > > following one. > > > importthreading > > import sys > > import time > > > def hello(): > > i=0 > > try: > > while i > print "hi" > > time.sleep(1) > > i+=1 > > except KeyboardInterrupt: > > print 'KeyboardInterrupt' > > raise KeyboardInterrupt > > > try: > > thread=threading.Thread(target=hello,args=()) > > thread.start() > > except KeyboardInterrupt: > > print 'KeyboardInterrupt' > > raise KeyboardInterrupt > > > once program starts, problem is.. > > I am not able to abort the thread using (CTRL+C) KeyboardInterrupt. While > > running if I press CTRL+C, it won't generate any exception until the end of > > the execution. Once the execution gets over, it will give "Exception > > exceptions.KeyboardInterrupt in > 'C:\python25\lib\threading.py'> ignored" this message and exits. > > > I had gone through some documents, it says if a thread is joined with > > .join() method then we can't stop that process until it releases the lock > > what it acquired. But in the above program I didn't use .join() method but > > still I am not able to abort the thread. > > > Could you please suggest me how can I abort the thread at any point in time > > using CTRL+C. > > > > a terminate method is given here:http://sebulba.wikispaces.com/recipe+thread2 > > so you can terminate the thread by: > > (...) > t.start() > (...) > > while True: > try: > #some code > except KeyboardInterrupt: > t.terminate() > break > > Mathieu (For some reason the OP hasn't come through to groups.google.com.. odd) Note that it won't interrupt any blocked I/O, which is often what you need the most. If your threads are CPU-bound you can simply have them check a flag and exit if it becomes True. -- http://mail.python.org/mailman/listinfo/python-list The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you.
problem when reading file   (83 Views)
hi every one, i am new to python, and coz i want to write a handy command for my linux machine, to find a word in all the files which are under the current folder. the code is half done, but when i run it, it complain, and i don`t know why can anyone help me have a look at it here is the message it complain ======================================= file is : qt_plugins_3.3rc Traceback (most recent call last): File "./python_script/svn_grep.py", line 34, in searPatten(file,'are','no') File "./python_script/svn_grep.py", line 8, in searPatten openFile = open(file, 'r') IOError: [Errno 2] No such file or directory: 'qt_plugins_3.3rc' here are the code i wrote ---------------------------------------------------------------code begin #!/usr/bin/python import os import string def searPatten(file, patten, isCaseSensitive): openFile = open(file, 'r') lines = openFile.readlines() lineNum = 1 for text in lines : words = text.split() existed = 0 for word in words : if isCaseSensitive == 'yes' : if word.lower() == patten.lower(): existed = 1 break else: if word == patten : existed = 1 break if existed == 1: print "line : " + str(lineNum) + " " + text lineNum += 1 openFile.close() for root, dirs, files in os.walk(os.getcwd()): for file in files: print "=======================================" print "file is : " + file + "\n" searPatten(file,'are','no') ---------------------------------------------------------------code end
Re: threading   (176 Views)
2008/8/13 Parimala : > , > > I am using python2.5.1 version to run my test scripts. I want to use > 'threading' module in my tests. As a startup program, I had run the > following one. > > import threading > import sys > import time > > def hello(): > i=0 > try: > while i print "hi" > time.sleep(1) > i+=1 > except KeyboardInterrupt: > print 'KeyboardInterrupt' > raise KeyboardInterrupt > > try: > thread=threading.Thread(target=hello,args=()) > thread.start() > except KeyboardInterrupt: > print 'KeyboardInterrupt' > raise KeyboardInterrupt > > once program starts, problem is.. > I am not able to abort the thread using (CTRL+C) KeyboardInterrupt. While > running if I press CTRL+C, it won't generate any exception until the end of > the execution. Once the execution gets over, it will give "Exception > exceptions.KeyboardInterrupt in 'C:\python25\lib\threading.py'> ignored" this message and exits. > > I had gone through some documents, it says if a thread is joined with > .join() method then we can't stop that process until it releases the lock > what it acquired. But in the above program I didn't use .join() method but > still I am not able to abort the thread. > > Could you please suggest me how can I abort the thread at any point in time > using CTRL+C. a terminate method is given here: http://sebulba.wikispaces.com/recipe+thread2 so you can terminate the thread by: (...) t.start() (...) while True: try: #some code except KeyboardInterrupt: t.terminate() break Mathieu
Re: reading plist files   (92 Views)
William Purcell wrote: > : not well-formed (invalid token): > line 1, column 8 so, what does line 1 of the file look like
ctypes and reading value under pointer passed as param of a callback   (93 Views)
I'm using C dll with py module and wanna read value (buffer of bytes) returned in py callback as parameter passed to dll function. -------------------------------------------------- def mycallback(data, size): # how to read data buffer here return 0 cbfunc = CFUNCTYPE(c_int, POINTER(c_uint8), c_int) mydll = cdll.somedll mdll.foo(cbfunct) --------------------------------------------------------------- Question: How to get bytes from the buffer passed to mycallback Let's assume that the buffer consist of 4 bytes 4 bytes 8 bytes. I tried unpack("ii8s", data[0]) and nothing. I tried different ctypes passed to callback and nothing. Any sugestions
Re: reading one byte from stdin   (97 Views)
Mark McDuff wrote: > I'm trying to read one byte from stdin, without the newline. > > If I try something like: > >>> import os, sys > >>> os.read(sys.stdin.fileno(),1) > > I can input a character, but then I have to press enter, which leaves a > newline character in the stdin buffer and requires two keypresses. Is > there any way to read only one keypress in a simple manner (i.e. no > curses) in addition to the cookbook article Diez posted, there's also a FAQ entry about this: http://effbot.org/pyfaq/how-do-i-get...-at-a-time.htm
start reading from certain line   (105 Views)
I am a starter in python and would like to write a program that reads lines starting with a line that contains a certain word. For example the program starts reading the program when a line is encountered that contains 'item 1' The weather is nice Item 1 We will go to the seaside .... Only the lines coming after Item 1 should be read
reading from list with paths   (148 Views)
, I would like to read and print files, of which the complete filepaths are mentioned in another textfile. In this textfile (list.txt) are for example the following paths: /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_1LG_f01.TextGrid /data/chorec/chorec-nieuw/s01/S01C001M1/ S01C001M1_1LGPseudo_f01.TextGrid /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_AVI1_f01.TextGrid I know how to open and read one file in my current directory, but after trying to find this out my self, I give up... I already got one answer for this question, but it did not work
reading from a gzip file   (94 Views)
, I have a gzip file and I try to read from this file withe the next statements: gunziped_file = gzip.GzipFile('gzip-file') input_file = open(gunziped_file,'r') But I get the nezt error message: Traceback (most recent call last): File "read_sfloc_files.py", line 131, in input_file = open(gunziped_file,'r') TypeError: coercing to Unicode: need string or buffer, instance found I think that I do some mistake. Would some body tell me what is my mistake Nader
Confusion with weakref, __del__ and threading   (94 Views)
On Jun 11, 10:43 am, George Sakkis wrote: > On Jun 11, 1:40 am, Rhamphoryncus wrote: > > The trick here is that calling proxy.sleep(0.01) first gets a strong > > reference to the Mystery instance, then holds that strong reference > > until it returns. > > Ah, that was the missing part; I thought that anything accessed > through a proxy didn't create a strong reference. The good thing is > that it seems you can get a proxy to a bounded method and then call it > without creating a strong reference to 'self': That's not right. Of course a bound method has a strong reference to self, otherwise you'd never be able to call it. There must be something else going on here. Try using sys.setcheckinterval(1) to make threads switch more often. > > num_main = num_other = 0 > main_thread = threading.currentThread() > > class MysterySolved(object): > > def __init__(self): > sleep = weakref.proxy(self.sleep) > self._thread = threading.Thread(target=target, args=(sleep,)) > self._thread.start() > > def __del__(self): > global num_main, num_other > if threading.currentThread() is main_thread: > num_main += 1 > else: > num_other += 1 > > def sleep(self, t): > time.sleep(t) > > def target(sleep): > try: sleep(0.01) > except weakref.ReferenceError: pass > > if __name__ == '__main__': > for i in xrange(1000): > MysterySolved() > time.sleep(.1) > print '%d __del__ from main thread' % num_main > print '%d __del__ from other threads' % num_other > > ========================================== > Output: > 1000 __del__ from main thread > 0 __del__ from other threads > >
the pipe reading in Thread dose not work.   (72 Views)
#!/usr/bin/env python # -*- coding: utf-8 -*- import string, sys from threading import Thread import os import time class test_pipe(Thread): def __init__(self, fd): Thread.__init__(self) self.testfd = fd def run(self): print "started thread begin -----" while True: buf = self.testfd.read() print "receive %s" % (buf) time.sleep(1) #print "hoho" if __name__ == "__main__": stdin_r, stdin_w = os.pipe() #stdout_r, stdout_w = pipe() f_w = os.fdopen(stdin_w, "w", 0) thrd = test_pipe(os.fdopen(stdin_r, "r", 0)) thrd.start() time.sleep(1) while True: f_w.write("help\r\n") time.sleep(1) thrd.join() -------------------------------------------- well, I want the following small test about pipe() in thread(). OK, I write to the pipe in the main thread, and I created a new thread for reading from the pipe, then it will print what it received from the pipe(). But, it seems it block at the "self.testfd.read()". So, is there and suggestion and explaination about it
threading - race condition?   (87 Views)
i'm getting the wrong output for the 'title' attributes for this data. the queue holds a data structure (item name, position, and list to store results in). each thread takes in an item name and queries a database for various attributes. from the debug statements the item names are being retrieved correctly, but the attributes returned are those of other items in the queue - not its own item. however, the model variable is not a global variable... so i'm not sure what's wrong. i've declared a bunch of worker threads (100) and a queue into which new requests are inserted, like so: queue = Queue.Queue(0) WORKERS=100 for i in range(WORKERS): thread = SDBThread(queue) thread.setDaemon(True) thread.start() the thread: class SimpleDBThread ( threading.Thread ): def __init__ ( self, queue ): self.__queue = queue threading.Thread.__init__ ( self ) def run ( self ): while 1: item = self.__queue.get() if item!=None: model = domain.get_item(item[0]) logger.debug('sdbthread item:'+item[0]) title = model['title'] scraped = model['scraped'] logger.debug("sdbthread title:"+title) any suggestions
future multi-threading for-loops   (64 Views)
Some iterables and control loops can be multithreaded. Worries that it takes a syntax change. for X in A: def f( x ): normal suite( x ) start_new_thread( target= f, args= ( X, ) ) Perhaps a control-flow wrapper, or method on iterable. @parallel for X in A: normal suite( X ) for X in parallel( A ): normal suite( X ) Discussion presued about multi-core systems. ow user certain control over what runs on multi-core. Clearly, not generally applicable. -- But, from __future__ import does change syntax.
Curses and Threading   (80 Views)
I am writing a program that uses curses and threading. I am working on displaying a clock in the upper right hand corner of the screen. I have only one thread at the moment, that gets the time and displays it in curses. To make it easier to debug right now, the program starts curses in a try: clause then starts the thread which runs for 10 iterations displaying the time every second. Then the thread exits, and the program is supposed to run the finally: clause to clean up the terminal. I also have set curs_set(0) so the cursor is invisible. What happens is that everything starts fine but the cursor is visible. It runs for the 10 seconds then quits without restoring the terminal to working order. I am trying this on a Fedora 4 computer have also tried it on a Fedora 8 one with same results. I have tried searching but Google doesn't find anything using both curses and threading. The only thing I can find regarding both is that curses seems to block when waiting for input, but I do not have any input yet. Below is what I have right now: #! /usr/bin/env python import curses import threading import time class cadtime(threading.Thread): def run(self): x=0 while x
Re: Zipfile content reading via an iterator?   (82 Views)
En Tue, 29 Jan 2008 11:06:12 -0200, Tim Chase escribi: > Just to follow up on this, I dropped the the 2.6 version of > zipfile.py in my project folder (where the machine is currently > running Python2.4), used the ZipFile.open() and it worked fine. > [...] > Anyways, thanks to Gabriel (and all the authors of Python > zipfile.py library) for the solution. I just bring attention to the upcoming feature. credit should go to the patch author, Alan McIntyre. -- Gabriel Genellina
python and multithreading problem   (146 Views)
Hi all, I made an application that use multithreading (indifferently importing thread or threading module) , but when I call some wrapped modules (with swig) from my application they run like there is only a single thread (and my application gui ,made with wxPython, freezes). If I use other modules not wrapped, but created for test that multithread works, and gui is not freezing are ok. Modules that wrap DLL are not my product but are created by another developer with VS.NET, and the only thing I can think is that they're builded without multithreaded compiler option. Can it be another cause for this behaviour, can this explanation be correct maybe also swig have a multithreading option.
Re: Zipfile content reading via an iterator?   (88 Views)
>>> I'm dealing with several large items that have been zipped up to >>> get quite impressive compression. However, uncompressed, they're >>> large enough to thrash my memory to swap and in general do bad >>> performance-related things. I'm trying to figure out how to >>> produce a file-like iterator out of the contents of such an item. >> >> The Time Machine in action again - that's already done, but in SVN. You >> want the new ZipFile.open(filename) method, which returns a file-like >> object. > >
Problem reading csv files   (92 Views)
I am trying to read a csv file using csv.reader. The file is created using Open Office and saved in Excel format. import csv reader = csv.reader(open('test.xls')) for row in reader: print row It however throws the exception _csv.Error: : line contains NULL byte Any idea whats going wrong here
Re: reading list of list to a file   (78 Views)
--- caroliina wrote: > > i made a list of lists but i cant write it into a > file. how do i get the > first string in a sublist > -- Try doing this: print list_of_lists print list_of_lists[0] print list_of_lists[0][0] print list_of_lists[0][0][0] It might give you some insight. If you're still stuck after that, it would help if you posted a little bit of your code. Good luck! ____________________________________________________________________________________ Looking for last minute shopping deals Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsea...egory=shopping
Re: instead of reading cookies (plan B)   (85 Views)
En Tue, 11 Dec 2007 17:34:50 -0300, Vincent Hirth escribi: > I was just thinking of an alternative to reading cookies directly - at > least > in my case. What if I create a PHP file that contains the cookies in 2 > lines, such as this > (To make it more clear --- begin of file --- Myusername Mypassword --- end of file --- > What would the python script look like if I wanted to open the file and > put > the 2 values in variables from __future__ import with_statement with open(filename, "r") as f: username = f.readline().strip() password = f.readline().strip() The above answers your specific question, but I don't see any relation with cookies or PHP. -- Gabriel Genellina