简体   繁体   English

删除特定行python之前的所有行

[英]Deleting all lines before a specific line python

I have a file- 我有一个档案

First Line
Second Line
Third Line
Fourth Line
Fifth Line
Sixth Line

Now I want to write the contents of the file after the fourth line. 现在,我想在第四行之后写入文件的内容。 therefore the new file would be- 因此,新文件将是-

Fifth Line
Sixth Line

My attempt- 我的尝试-

cnt=0
for root, dirs, files in os.walk(currentdir):
    for name in files:



        f = open(root+"/"+name,'r')
        lines = f.readlines()
        f.close()
        f = open(os.path.join(root, name),"w")
        for line in lines:
            cnt+=1 
            if line =="fourth Line"+"\n":
                break:
        f.seek(cnt)
        f.write(line)
        f.close()
for path, dirs, files in os.walk(currentdir):
    for name in files:
        with open(os.path.join(path, name)) as f:
            data = f.readlines()
        pos = data.index("Fourth Line\n")
        with open(os.path.join(path, name), 'w') as f:
            f.writelines(data[pos:])

You can just get the lines in a file, slice the array, and then write them back in: 您可以只获取文件中的行,对数组进行切片,然后将其写回:

with open('filename.txt', 'r+') as f:
    lines = f.readlines()
    f.write(lines[5:])

If you wanted to you could read and write in separate with blocks, or whatever else. 如果您愿意的话,可以with块的代码或其他代码分别with读写。

You can load the file lines to a list, and after split the list keeping only the lines you want and saving on the file. 您可以将文件行加载到列表中,然后在拆分列表后仅保留所需的行并保存在文件中。 Example, if you want the content after the 4th line: 例如,如果您想要第四行之后的内容:

f = open("file.txt", 'r')
lines = f.readlines()
f.close()
lines = lines[4:]
f = open("file.txt", 'w')
f.write(lines)
f.close()

you could always place a counter in loop, and start writing the second file when counter reaches 4. Something like: 您可以始终将一个计数器放在循环中,并在计数器达到4时开始写入第二个文件。

with open('a', 'w') as a, open('b', 'w') as b:
do_something()

or: 要么:

f1 = open(path, 'w')
f1.write(data)
f1.close()
counter += 1
if counter >= 4:
f2 = open(path, 'w')
f2.write(data)
f2.close()

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

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