readlines()

md mark at deverter.net
Wed Aug 18 12:10:18 EDT 2004


I am not sure which name is designating your source text (db1 or getdata 
?).  If it is 'getdata' then you will need to iterate over the file 
object to grab all of the lines.  Try this:

  for line in db1:
     (ip, mac) = string.split(line)
      print 'ip is ', ip
      run = 'dhcpacct --ip=%s  > tt1'
      os.system(run)
      getdata = open('tt1', 'r')
      data=[]
      for line in getdata.readlines():
	data.append(line)
      print 'data[0] is', data[0]
      print 'data[3] is', data[3]
      getdata.close()

Hope this helps,
Mark d.


Yong Wang wrote:
> Hi,
>    I use readlines() to read one data file. Python automatically parses the read contents
> into a list of lines. When I used list[0] to print out the 1st line, it is ok. When I use
> the list index 2 to print out the 2nd line , there is an error mesage. I only need one line of
> input data file in the middle of the file. For example, I have data file like: 
> ---------------------------------------------------------------------------
>           Timestamp: Sat Aug  7 11:14:57 AM
>     Adapter Address: 00:60:08:2A:C9:5A
>          IP Address: 165.91.10.244
>        Directory ID: 0675392c736079cfd81a55028df3cb43
>         Domain Name: bdanwood.dsl.tamu.edu
>     DHCP/NIM Action: lease renewed
>            Comments: 
> ---------------------------------------------------------------------------
>           Timestamp: Sat Aug  7 11:15:56 PM
>     Adapter Address: 00:60:08:2A:C9:5A
>          IP Address: 165.91.10.244
>       Directory ID: 0675392c736079cfd81a55028df3cb43
>         Domain Name: bdanwood.dsl.tamu.edu
>     DHCP/NIM Action: lease renewed
>            Comments: 
> ---------------------------------------------------------------------------
> 
> I have some codes:
>     .......
> for line in db1:
>    (ip, mac) = string.split(line)
>     print 'ip is ', ip
>     run = 'dhcpacct --ip=%s  > tt1'
>     os.system(run)
>     getdata = open('tt1', 'r')
>     data    = getdata.readlines()
>     print 'data[0] is', data[0]
>     print 'data[3] is', data[3]
>     getdata.close()
>  
> When run the codes, I got:
> data[0] is ---------------------------------------------------------------------------
> 
> data[3] is
> Traceback (innermost last):
>   File "com1", line 64, in ?
>     print 'data[3] is', data[3]
> IndexError: list index out of range
> 
>     How can I fix it ?
> 
>     Thanks,
> 
> 



More information about the Python-list mailing list