[Python] Help with code please! Also 'enumerate'

Watch
Sogstar
Badges: 8
Rep:
?
#1
Report Thread starter 3 years ago
#1
Hi guys, I am trying to code this bit where it will print specific lines from a text file. I read up on something called 'enumerate' but not at all sure how I can use this to implement a specific line printer. Also, if you decide to help me w/ the code, could you please explain what each line of code does (not the basic stuff like print for variables etc). Thanks in advance!
1
reply
RonnieEl7
Badges: 11
Rep:
?
#2
Report 3 years ago
#2
You could use a for loop if you are trying to print lines that have a specific word. Do something like this:


file = open("file") Opens the file
lines = file.readlines() Assigns the read file to the variable 'lines'
for line in lines: goes through each line in the file read
if ("your string")in line: if your string is in the line it will print it
print line
file.close() closes the file
0
reply
Cyberspace
Badges: 9
Rep:
?
#3
Report 3 years ago
#3
Assuming you are on a Python version above 2.5 (you should be), the following snippet should work.

Image

edit: By the way, enumerate() just creates an iterator, which will go through a list one-by-one
0
reply
X

Quick Reply

Attached files
Write a reply...
Reply
new posts
Back
to top
Latest
My Feed

See more of what you like on
The Student Room

You can personalise what you see on TSR. Tell us a little about yourself to get started.

Personalise

Do you feel the grades you will receive this year will be fair?

Yes I feel the grades I will receive will be fair (40)
22.73%
No, I don't feel the grades I will receive will be fair (86)
48.86%
I'm unsure (50)
28.41%

Watched Threads

View All