code
Python exercise: Print every other line from a file
Python exercise
*************
Episode: 6
Level: Beginner
Working with text files in Python is very easy and it does not require any additional library. To open a file for reading you just need to do:
f = open("somefile.txt", "w")
and for writing to a file do next:
f.write("some line")
When you are done just close the file with:
f.close()
Write Python script which prints every other line from a file.
You will need a counter and you will need to check that counter is even or odd number. Here is one of the possible solutions.
with open('somefile.txt', 'r') as f:
counter = 0
for line in f:
counter += 1
if counter % 2 == 0:
print(line)
f.close()
You can also write separate function to check if counter is odd or even number.
o_o


Post a Comment
1 Comments
nice
ReplyDeleteThanks for sharing your thoughts !