The Student Room Group

Coding help? Please help me with reading text files!!!

Hi!

So basically, I need to read separate lines from a text file depending on the user's input. I can read the whole text file and all but, I need to make my code a bit more efficient so instead of having like 5 separate text files , I need to have one with all the info.

So here is an example:

This is the content of the text file 'all_Colours':

1.Primary colours make up secondary colours
2.Colours are everywhere.
3.Wolfs are cool
4.Fruits are good for you.

Python Code:

primaryColours=['red', 'blue' , 'green' ]

colour=input("What is your fav colour?" )

if colour in primaryColours:
print("Here are some fun facts:" )
text_file=open("all_Colours.txt", "r" )
print (text_file.read()) ## Instead of reading the whole text file I only want to read lines 1 and 2. How do i do this??????
text_file.close()

Thank you for all the help :smile:
(edited 7 years ago)
What language is this?
Original post by The_JoKeR
What language is this?


It seems to be heavily, and incorrectly punctuated English.
Reply 3
oh python :colondollar:

Sorry, i'm a beginner, ignore my many mistakes. I know it's not perfect but i'm looking to improve and just figure this out.
Original post by bluepearl7
oh python :colondollar:

Sorry, i'm a beginner, ignore my many mistakes. I know it's not perfect but i'm looking to improve and just figure this out.

Ah sorry no help there then. Did Visual Basic and Javascript instead.
Original post by bluepearl7
## Instead of reading the whole text file I only want to read lines 1 and 2. How do i do this??????

text_file.readlines()[0:2]
OP are you self studying or what ?

Posted from TSR Mobile
Reply 7
Original post by Push_More_Button
text_file.readlines()[0:2]


Thankyou! :smile:
I get it now.

Original post by nerdling_CompSci
OP are you self studying or what ?

Posted from TSR Mobile


Not really. I'm a student trying to do coursework.

Quick Reply

Latest

Trending

Trending