简体   繁体   English

Python将某些行从一个文件复制到另一个文件

[英]Python copying certain lines from one file to another

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? 在这种情况下,我只想复制前109行,但也想知道如何复制不同的特定行,例如复制1,5,38和200行?

Use enumerate to get the line number while iterating over the file: 遍历文件时,使用enumerate获取行号:

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). 请注意,n从零开始,我假设您从1开始计数,这就是为什么我要测试(n + 1)。

You can use enumerate to find out line numbers and write them accordingly: 您可以使用enumerate找出行号并相应地编写它们:

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 请注意,行号从0开始。这就是为什么linenum+1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM