简体   繁体   English

从现有文件中将行写入新文件

[英]Writing lines to new file from existing file

I have a file with close to 5000 lines (il3). 我有一个接近5000行(il3)的文件。 I want to write the first 7 lines and then a certain number of lines at the end of the file to a new file (il3NEW). 我想将文件末尾的前7行然后一定数量的行写入新文件(il3NEW)。 I am able to write the first 7 lines, but when I try to write the later lines I am not finding anything that works. 我能够编写前7行,但是当我尝试编写后面的行时,我找不到任何有用的东西。

Not all files I will be working with are identical so I do not simply want to look at the file and pick line numbers and write, I need to write lines from the original file 'il3', to the new file 'il3NEW', starting at a specific line where a certain word is mentioned then all the way to the end of the file. 并非所有我将使用的文件都是相同的,所以我不只是想查看文件并选择行号并写入,我需要将原始文件'il3'中的行写入新文件'il3NEW',开始在提到某个单词的特定行,然后一直到文件末尾。

I have successfully opened 'il3' as well as a blank new file (il3NEW). 我已成功打开'il3'以及一个空白的新文件(il3NEW)。 I used a for loop to write the first 7 lines. 我使用for循环来编写前7行。 When I try to write based on the location of a certain word in 'il3', I do not know how to identify that line number and then use that line number to write the lines from there to the end of the file to the 'il3NEW'. 当我尝试根据'il3'中某个单词的位置进行书写时,我不知道如何识别该行号,然后使用该行号将行从那里写到文件的末尾到'il3NEW ”。

This is what I have that works: 这就是我的工作:

il3= open("il3dta",'r')

il3NEW= open("il3dtaNEW",'w')

for i in range(7):
    m=il3.readline()
    il3NEW.write(m)

il3.close()
il3NEW.close()

I also have the following that adds the immediate line: 我还有以下添加立即行:

for i in range(5000):
    m=il3.readline()
    if m == ' -1    TREE  POINTS(=1),OTHERWISE NO TREE\n':
        il3NEW.write(m)

However, I want all following lines as well. 但是,我也想要所有以下行。 How do I get it to loop through all lines after and write those as well? 如何让它循环遍历所有行并写入它们?

I also noticed that whenever I write anything before the for loop and between the open statement, the for loop no longer works. 我还注意到,每当我在for循环之前和open语句之间写任何东西时,for循环都不再有效。 For example, if I try to define some variables: 例如,如果我尝试定义一些变量:

#lines=il3.readlines()
#searchquery = ' -1    TREE  POINTS(=1),OTHERWISE NO TREE\n'

The for loops no longer work and my new file is empty. for循环不再有效,我的新文件为空。

It would also be nice if the second loop I have for the later lines were to loop through the entire file without having to write 5000. I tried: 如果后面的第二个循环用于循环遍历整个文件而不必编写5000,那也很好。我试过:

for i in range(len(il3.readlines(  ))):
    m=il3.readline()
    if m == ' -1    TREE  POINTS(=1),OTHERWISE NO TREE\n':
        il3NEW.write(m)

But that does not work. 但这不起作用。 If I try to define the number of lines as above, it results in a blank file. 如果我尝试按上面的方式定义行数,则会生成一个空白文件。 Any help in fixing this would be much appreciated! 任何帮助解决这个问题将非常感谢! I am new to Python so I apologize for the basic question, but I couldn't find questions with the same issues. 我是Python的新手,所以我为基本问题道歉,但我找不到有同样问题的问题。 Thanks!! 谢谢!!

If I understand correctly you can modify your approach a bit to have a flag HaveFoundTheLineImLookingFor which is True if you found your special line. 如果我理解正确你可以修改你的方法有一个标志HaveFoundTheLineImLookingFor如果你找到你的特殊线,这是真的。 Then, if this is true, we write every line with an added or to your if statement: 然后,如果这是真的,我们用添加or if语句写每一行:

HaveFoundTheLineImLookingFor = False
for i in range(5000):
    m=il3.readline()
    if (m == ' -1    TREE  POINTS(=1),OTHERWISE NO TREE\n'  or HaveFoundTheLineImLookingFor ):
        il3NEW.write(m)
        HaveFoundTheLineImLookingFor  = True

An even better approach would be to not limit ourselves to files with 5000 lines: 更好的方法是不限制自己使用5000行的文件:

HaveFoundTheLineImLookingFor = False
with open('il3dta') as MyFile:
    for i, line in enumerate(MyFile):
        if(i < 7):
            il3NEW.write(line)
        if(HaveFoundTheLineImLookingFor  ):
            il3NEW.write(line)
        if(line == ' -1    TREE  POINTS(=1),OTHERWISE NO TREE\n' and !HaveFoundTheLineImLookingFor  ):
            il3NEW.write(line)
            HaveFoundTheLineImLookingFor  = True

Please make a habit of using context managers with files. 请养成使用上下文管理器和文件的习惯。

with open('il3dra') as il3, open('il3dtaNEW', 'w') as il3_new:
    found = False
    for line_idx , line in enumerate(il3):
        if line.strip() == ' -1    TREE  POINTS(=1),OTHERWISE NO TREE':
            found = True

        if found or line_idx < 7:
            il3_new.write(line)

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

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