1

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?:)

Danny_ds
  • 10,507
  • 1
  • 17
  • 42
hektor102
  • 47
  • 5
  • Take a look at this - https://stackoverflow.com/questions/14257373/skip-the-headers-when-editing-a-csv-file-using-python – Employee Jan 17 '19 at 09:08
  • Possible duplicate of [How can I read a csv file after a certain pattern in Python?](https://stackoverflow.com/questions/54192970/how-can-i-read-a-csv-file-after-a-certain-pattern-in-python) – Chris Jan 17 '19 at 09:13

1 Answers1

0

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.

hektor102
  • 47
  • 5
U11-Forward
  • 41,703
  • 9
  • 50
  • 73