Reputation: 1368
I want to copy specific lines from one file to another.
I can copy the entire file quite easily with:
or_profile_file = open('or_profile.prof')
new_profile_file = open('new_profile.prof','w')
for line in or_profile_file:
new_profile_file.write(line)
or_profile_file.close()
new_profile_file.close()
How can I copy only specific lines though? In this case I want to copy only the first 109 lines, but would also be interested in knowing how to copy different specific lines, for instance copying lines 1,5,38 and 200?
Upvotes: 0
Views: 180
Reputation: 9636
You can use enumerate to find out line numbers and write them accordingly:
or_profile_file = open('or_profile.prof')
new_profile_file = open('new_profile.prof','w')
lines_to_write = [1, 5, 38, 200]
for linenum, line in enumerate(or_profile_file):
if linenum+1 in lines_to_write:
new_profile_file.write(line)
or_profile_file.close()
new_profile_file.close()
Do note that line numbers start from 0. That's why it's linenum+1
Upvotes: 1
Reputation: 77261
Use enumerate to get the line number while iterating over the file:
desired_lines = [1, 5, 38, 200]
for n, line in enumerate(or_profile_file):
if (n+1) in desired_lines:
new_profile_file.write(line)
Note that n starts at zero, I assume you are counting from 1, that is why I test for (n+1).
Upvotes: 1