简体   繁体   中英

How to skip lines until find the 'keyword' in txt file and save rest as csv? python

I have a txt file in csv form but with unnecessary few lines on top. I need to skip a few 8-10 lines (it depends from file), after "[App]" line.

The file looks like this:

1, trash
2, trash
3, [APP]
4
.
.
.
100 

and I need to save the 4-100 lines as csv where 4 will be headers and rest are rows.

What is the best way? I tried a: "with open"

with open('som.txt', 'r') as fin:
    data = fin.read().splitlines(True)
with open('som.txt', 'w') as fout:
    fout.writelines(data[7:])

    print(data)

So, I have now data list and its ok, but that code skip lines after a number of lines, not specific word. Also, I can't save this list as properly CSV file; c Can u help?:)

Use readlines , then use seek , and writelines :

with open('some.txt', 'r+') as f:
    text=f.readlines()
    f.seek(0)
    f.writelines(text[[i for i, s in enumerate(mylist) if '[APP]' in s][0]:])

Your file will be now as expected, and another plus that it doesn't do it by index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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