Click here to Skip to main content
15,891,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
im trying to print the first word of very line (expect the first line) but i keep getting synthax error. It's from a text file i created. Here is the code/text

We are hungry.
There is an apple.
There is an orange.
Now we are thirsty.


What I have tried:

Python
filename = "firstthing.txt" 
file = open(filename)
text = file.read
lines = text.split('\n')

for line in lines:
     line.split(" ",1)[0]
     print " There are the lines:"


What am i doing wrong? How do i write it properly?
Posted
Updated 20-Mar-18 22:38pm
v4
Comments
Maarten Kools 20-Mar-18 18:02pm    
What's your syntax error? Not sure if you're actually doing it (your code isn't formatted in your question), but you need to indent the code block for the for loop, see also https://wiki.python.org/moin/ForLoop
Member 13693496 20-Mar-18 18:23pm    
it won't let me indent it and the synthax error was 'builtin_function_or_method' object has no attribute 'split'. I dont know why it is saying that but do you have any clue on how to properly write the code because mines seems right yet an error..
Maarten Kools 20-Mar-18 18:26pm    
oh, so it's on the first split probably. Try file.read()
Member 13693496 20-Mar-18 20:33pm    
yea i have and still no solution
PIEBALDconsult 20-Mar-18 21:55pm    
I don't know Python, but I'm reasonably sure you need parentheses on the call to read .

1 solution

Based on these:
python - How to skip first element in `for` loop? - Stack Overflow[^]
Skip first entry in for loop in python? - Stack Overflow[^]
you need to use next function[^]

Python
lines = text.split('\n')
next(lines)
for line in lines:
     print line.split(" ",1)[0]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900