Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Line indexing in Python

4 views
Skip to first unread message

seafoid

unread,
Dec 18, 2009, 10:42:19 AM12/18/09
to pytho...@python.org

Hi Guys,

When python reads in a file, can lines be referred to via an index?

Example:

for line in file:
if line[0] == '0':
a.write(line)

This works, however, I am unsure if line[0] refers only to the first line or
the first character in all lines.

Is there an easy way to refer to a line with the first character being a
single letter that you know?

Thanks in advance,
Seafoid.
--
View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26845253.html
Sent from the Python - python-list mailing list archive at Nabble.com.

Richard Thomas

unread,
Dec 18, 2009, 10:51:12 AM12/18/09
to

'for line in file' goes through the lines of the file. 'line[0]' is
then the first character of that line. You'll need to index them
manually, for which you should use a dictionary:

index = {}
for line in file:
index[line[0]] = line
a.write(index['0'])

Richard.

Steve Holden

unread,
Dec 18, 2009, 11:12:08 AM12/18/09
to pytho...@python.org
seafoid wrote:
> Hi Guys,
>
> When python reads in a file, can lines be referred to via an index?
>
> Example:
>
> for line in file:
> if line[0] == '0':
> a.write(line)
>
> This works, however, I am unsure if line[0] refers only to the first line or
> the first character in all lines.
>
Each time around the loop the variable "line" contains the current line
from the file. Thus line[0] is the first character of the current line.

If your intent is to print all lines beginning with "0" then your code
will work.

> Is there an easy way to refer to a line with the first character being a
> single letter that you know?
>

You might express it more readably as

for line in file:
if line.startswith("0"):
a.write(line)

This seems to express the intent of your code somewhat more directly.

regards
Steve

--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

seafoid

unread,
Dec 18, 2009, 11:27:56 AM12/18/09
to pytho...@python.org

Thanks for that Richard and Steve.

I have another question.

fname = raw_input('Please enter the name of the file: ')

# create file objects

blah = open(fname, 'r')
a = open('rubbish', 'w')

for line in blah:


if line.startswith("0"):
a.write(line)

elif line.endswith("0"):
lists_a = line.strip().split()
print lists_a
elif line.startswith("0"):
lists_b = line.strip().split()
print lists_b

Essentially, I wish to take input from a file and based on the location of
zero, assign lines to lists.

Any suggestions?

Seafoid.

--
View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26845949.html

seafoid

unread,
Dec 18, 2009, 11:35:16 AM12/18/09
to pytho...@python.org

Thanks for that Richard and Steve!

Below is my full code so far:

for line in file:
if line.startswith("1"):


a.write(line)
elif line.endswith("0"):
lists_a = line.strip().split()
print lists_a

elif line.startswith("2"):
lists_b = line.strip().split()
print list_a

Essentially, I want to read in a file and depending on location of 0, 1, 2,
write to another file or create lists.

The above passes without error warning but does nothing (semantic error?).

Any Suggestions?

Thanks in advance,
Seafoid.
--
View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26846049.html

seafoid

unread,
Dec 18, 2009, 11:39:16 AM12/18/09
to pytho...@python.org

Thanks for that Richard and Steve!

Below is my full code so far:

for line in file:
if line.startswith("1"):
a.write(line)
elif line.endswith("0"):
lists_a = line.strip().split()
print lists_a
elif line.startswith("2"):
lists_b = line.strip().split()

print list_b

Lie Ryan

unread,
Dec 18, 2009, 11:54:10 AM12/18/09
to
On 12/19/2009 3:27 AM, seafoid wrote:
>
> Thanks for that Richard and Steve.
>
> I have another question.

What's the question?

> fname = raw_input('Please enter the name of the file: ')
>
> # create file objects
>
> blah = open(fname, 'r')
> a = open('rubbish', 'w')
>
> for line in blah:
> if line.startswith("0"):
> a.write(line)
> elif line.endswith("0"):
> lists_a = line.strip().split()
> print lists_a

The following block is a dead code; the block will never be executed
since if line.startswith("0") is true, the control will fall to the
a.write(line) block and this block is skipped.

seafoid

unread,
Dec 18, 2009, 12:33:43 PM12/18/09
to pytho...@python.org

Thanks for that Lie.

I had to have a think about what you meant when you referred to control
going to a.write(line).

Have you any suggestions how I may render this code undead or should I scrap
it and create something new?

My confusion and ineptitude is perhaps explained by my being a biologist :-(

Thanks,
Seafoid.
--
View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26846854.html

Lie Ryan

unread,
Dec 18, 2009, 1:18:11 PM12/18/09
to
On 12/19/2009 4:33 AM, seafoid wrote:
>
> Thanks for that Lie.
>
> I had to have a think about what you meant when you referred to control
> going to a.write(line).

and if-elif-elif-... chain is executed sequentially and when a match is
found, the rest of the chain is skipped. Your code:

if line.startswith("0"):
# BLOCK 1 #
elif line.endswith("0"):
# BLOCK 2 #
elif line.startswith("0"):
# BLOCK 3 #

BLOCK 3 never gets executed, since if line.startswith("0") is true, your
BLOCK 1 is executed and the rest of the if-elif chain is skipped.


> Have you any suggestions how I may render this code undead or should I scrap
> it and create something new?

I still don't get what you want to do with the code, but to make it not
dead you can either:

for line in blah:
if line.startswith("0"):
a.write(line)

lists_b = line.strip().split()
print lists_b

elif line.endswith("0"):
lists_a = line.strip().split()
print lists_a

or this:

for line in blah:
if line.startswith("0"):
a.write(line)

if line.endswith("0"):
lists_a = line.strip().split()
print lists_a

elif line.startswith("0"):
lists_b = line.strip().split()
print lists_b

depending on which one seems more readable to you.

seafoid

unread,
Dec 18, 2009, 1:22:56 PM12/18/09
to pytho...@python.org

Hi Guys,

It has been point out that it is difficult for anyone to provide suggestions
if I do not outline more clearly my input file and an example of what I wish
to do with it (Thanks Rory!).

I mentioned it in this thread (Is creating different threads bad etiquette?
If so, lesson learned!):

http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-to26837682.html

Hope you guys may have some suggestions as I am stumped!

Thanks,
Seafoid :-)

seafoid wrote:
>
> Hi Guys,
>
> When python reads in a file, can lines be referred to via an index?
>
> Example:
>

> for line in file:


> if line[0] == '0':
> a.write(line)
>
> This works, however, I am unsure if line[0] refers only to the first line
> or the first character in all lines.
>

> Is there an easy way to refer to a line with the first character being a
> single letter that you know?
>

> Thanks in advance,
> Seafoid.
>

--
View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26847598.html

Rory Campbell-Lange

unread,
Dec 18, 2009, 1:01:04 PM12/18/09
to seafoid, pytho...@python.org
On 18/12/09, seafoid (fitz...@tcd.ie) wrote:
> Have you any suggestions how I may render this code undead or should I scrap
> it and create something new?

It might be easier for us to help you if you give us an example of your
input file and a clearer description of what you are trying to do with
the output from your programme.

--
Rory Campbell-Lange
ro...@campbell-lange.net

Campbell-Lange Workshop
www.campbell-lange.net
0207 6311 555
3 Tottenham Street London W1T 2AF
Registered in England No. 04551928

Rory Campbell-Lange

unread,
Dec 18, 2009, 4:22:54 PM12/18/09
to seafoid, pytho...@python.org
On 18/12/09, seafoid (fitz...@tcd.ie) wrote:
> http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-to26837682.html

Your specification is confusing. However I suggest you break it down
the code so that the steps in your programme are logical. Good luck.

# example psuedocode
headers = {}
header_clauses = {}
current_header = None

def header_parser (input):
split input into parts
make unique header desciptor
check not in headers else abort with error (?)
add descriptor to headers hash
# eg descriptor 1 = [attrib1, attrib2, attrib3]
return descriptor

def clause_parser (input, current_header):
if current_header is None: abort
split clause into parts
store in array in header_clauses [current_header]
# this will make a data structure like this:
# header_clauses = {
# descriptor1 = {[ clause parts ], [ clause parts ], ... }
# descriptor2 = {[ clause parts ], [ clause parts ], ... }

def comment_parser (input)
pass

# now run over the file
for l in lines:
if l[0] == 'c':
comment_parser(l)
elif l[0] == 'p':
current_header = header_parser(l)
else:
clause_parser(l, current_header)

# now that we have stored everything, check the data
for h in headers:
attrib1, attrib2, attrib3 = headers[h]
for c in header_clauses:
iterate over the arrays of clause parts either adding them
up or comparing them to the header attributes

--
Rory Campbell-Lange
Director

seafoid

unread,
Dec 18, 2009, 4:24:54 PM12/18/09
to pytho...@python.org

Hey folks,

Is it possible to assign a list within a nested list to a variable?

Example:

l = [['1', '2', '3'], ['4', '5', '6']]

for i in l:
if i[0][1] == '1':
m = i

Indeed, I generally do not understand how to assign variables within a loop!

Is there an easy way to 'flatten' a nested list and assign the lists to
variables?

Thanks,
Seafoid.
--
View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26849921.html

seafoid

unread,
Dec 18, 2009, 4:26:58 PM12/18/09
to pytho...@python.org

Rory,

You are a gentleman!

Thank you very much for your suggestion!

Kind Regards,
Seafoid.

> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

--
View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26849944.html

r0g

unread,
Dec 21, 2009, 5:09:45 PM12/21/09
to
seafoid wrote:
> Hi Guys,
>
> When python reads in a file, can lines be referred to via an index?
>
> Example:
>
> for line in file:
> if line[0] == '0':
> a.write(line)
>
> This works, however, I am unsure if line[0] refers only to the first line or
> the first character in all lines.
>
> Is there an easy way to refer to a line with the first character being a
> single letter that you know?
>
> Thanks in advance,
> Seafoid.


If you want to know the index number of an item in a sequence you are
looping through (whether it be a file of lines or a list of characters,
whatever) use enumerate...

>>> for index, value in enumerate("ABCD"):
print index, value
...
0 A
1 B
2 C
3 D


If you want to extract an index number from the first part of of a given
line use split( split_character, maximum_splits_to_do ) and then angle
brackets to reference the first part (index 0)...


>>> a = "20 GOTO 10"
>>> int( a.split(' ',1)[0] )
20


Cheers,


Roger.

Steve Holden

unread,
Dec 22, 2009, 7:25:51 AM12/22/09
to pytho...@python.org
<nit>
those are brackets, not angle brackets
</nit>

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119

PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/

Lie Ryan

unread,
Dec 22, 2009, 12:42:28 PM12/22/09
to
On 12/22/2009 11:25 PM, Steve Holden wrote:
>> >
>> > If you want to extract an index number from the first part of of a given
>> > line use split( split_character, maximum_splits_to_do ) and then angle
>> > brackets to reference the first part (index 0)...
>> >
>> >
>>>>> >>>> a = "20 GOTO 10"
>>>>> >>>> int( a.split(' ',1)[0] )
>> > 20
>> >
> <nit>
> those are brackets, not angle brackets
> </nit>
>

<double_nit>
those [] are square brackets, not angle brackets
</double_nit>

r0g

unread,
Dec 22, 2009, 2:41:24 PM12/22/09
to


<nit++>
They're actually square brackets, "brackets" on its own is more commonly
used as a synonym for parentheses (round brackets). But yes, I did get
that wrong in the above ;)
</nit++>

Cheers,

Roger :)

MRAB

unread,
Dec 22, 2009, 7:13:58 PM12/22/09
to pytho...@python.org

<triple_nit>
[] are brackets, () are parentheses, {} are braces
</triple_nit>

0 new messages