On 20/02/2019 14:30, Mario Ontiveros wrote:
> Hello,
>     I am new to python and have been stuck on this for a while. What I am 
> trying to do is to remove rows with void, disconnected, and error on lines. 
> The code I have does that, the only problem is that it removes my header 
> because void is in header. I need to keep header.
> 
> Any help will be greatly appreciated.
> 
> with open("PSS.csv","r+") as f:
>     new_f = f.readlines()
>     f.seek(0)
>     for line in new_f:

I don't know how long your header is but assuming it is
only 1 line you can simply use slicing to remove the first
line:

      for line in new_f[1:]:

If the header is multi line simply change to the first line you need to
process, for example to remove 3 lines use new_f[3:]

>         if "Void" not in line:
>             if "Disconnected" not in line:
>                 if "Error" not in line:
>                    f.write(line)

This only writes the line if all three terms are present. Assuming thats
what you want it might be more obviously written as

if ("Void" in line and
   "Disconnected in line and
   "Error" in line):
      f.write(line)

You could also use a regex to search for all three and if its
a long file that will probably be faster since it only traverses
the list once. The snag is the regex gets complex if you need
all three in any order. But if you know the order in which
the terms arise it's probably the best option.

>     f.truncate()

While overwriting the original file works, it's slightly dangerous
in that you lose the original data if anything goes wrong.
The more usual way to do things is to create a new file for writing
then rename it to the original if, and only if, everything works.
You might even rename the original to .bak first to be really safe.

The other advantage of this approach is that you don't need the
readlines)() call but can just process the file line by line
directly which should also be faster.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to