Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Python Question

Options
  • 01-08-2012 5:26pm
    #1
    Registered Users Posts: 13


    Hi Folks,

    I am new to Python. I am looking for the best way to delete all lines from a file that contains characters.

    For example, from below, only User1, User2, User3 and User 4 would exist after processing. Notice User 4 has a space.

    5!pY
    "TmL
    c]+y?"
    |)}?E
    \e2g%
    User1
    User2
    User3
    User 4
    11-01-05
    [GO-B

    If anyone could point me in the right direction I'd greatly appreciate it.

    Thanks
    Tagged:


Comments

  • Registered Users Posts: 7,410 ✭✭✭jmcc


    Hi Folks,

    I am new to Python. I am looking for the best way to delete all lines from a file that contains characters.
    Check out the re module (Regex). You can use it to detect the characters you want to delete and then delete the line or don't write it to the output file. Basically you can do this (this is pseudocode):

    Open input file
    Open output file

    While there are lines in the input file:
    Read a line from input file
    Has it unwanted characters?
    (this is the regex part)
    if no:
    write file to output file

    Close input file
    Close output file


    http://docs.python.org/library/re.html
    http://docs.python.org/howto/regex.html

    There may be other ways but I think (with my limited knowledge of Python), the re module is the best way of doing it.

    Basically you would construct a regex of the characters that you want to filter and if the input line has any of these characters, it is ignored and not written to the output file. A line without these characters will be written to the output file.

    Regards...jmcc


  • Registered Users Posts: 13 BitsAndBytes


    Hi,

    thanks for the reply. I managed to get what I needed done.


Advertisement