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.
'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.
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/
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
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
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
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.
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
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.
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
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
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
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
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
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.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
<double_nit>
those [] are square brackets, not angle brackets
</double_nit>
<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 :)
<triple_nit>
[] are brackets, () are parentheses, {} are braces
</triple_nit>