question re file as sequence
Byron
DesertLinux at netscape.net
Sun Jul 11 10:19:31 EDT 2004
Hi Paul,
Here is how I would do this:
-----------------------------------
import string
counter = 0
f = open("c:\produce.txt", "r") # Obtain info from produce.txt file.
produce = f.readlines() # Store each line of text in a list called
produce.
while counter < len(produce):
if string.strip(produce[counter]) == "Fruit:": # Evaluate each line
in produce for a match.
print produce[counter + 1] # If matches, print next line.
counter = counter + 1 # Proceed to next item in text file.
-----------------------------------
However, there would be a much simplier way of doing this by changing
the data source slightly. See example:
Vegetable:spinach
Fruit:banana
Flower:Daisy
Fruit:pear
Here's how to parse this information and to find the fruits:
import string
f = open("c:\produce.txt", "r") # Open the file for reading.
category = []
for product in produce:
product = string.strip(product) # Remove the carriage return at
end of line.
category = category + [string.split(product, ":")] # Create a list [
[category, product], [category, product], [category, product] ] format.
# Display the items from the list.
for item in category:
if item[0] == "Fruit": # If category is "Fruit"
print item[1] # then display product from list.
-----------------------------------
Hope this helps!
Byron
---
Paul Rubin wrote:
> I have a file with contents like:
>
> Vegetable:
> spinach
> Fruit:
> banana
> Flower:
> Daisy
> Fruit:
> pear
>
> I want to print out the names of all the fruits. Is the following valid?
>
> f = open(filename)
> for line in f:
> if line == 'Fruit:\n':
> print f.readline()
>
> The issue here is that the sequence has been mutated inside the loop.
>
> If the above isn't good, anyone have a favorite alternative to doing
> it like that?
>
> Thanks.
More information about the Python-list
mailing list