Search code examples
pythonregexcsvfile-iooptparse

how to solve about regex file refining program?


I want to refine my csv file.

i imported fileinput, optparse, and re modules.

and loaded a csv file, and set if an word doesn't exist, delete it.

but i received blank file.

here is my code:

import fileinput
import optparse
import re

parser = optparse.OptionParser("usage%prog -d <directory>")
parser.add_option('-d', dest='directory', type='string', help='specify file path')

dname = options.directory

for line in fileinput.input(dname, inplace=1):
    if bool(re.match("\d\d\d\d",line)) == False:
        continue

my csv file contains like this:

2014,10,21....
2014,10,22....
asdfsadf

so i want to remove such as line 3.

what is wrong about my code? Any help will be very appreciating. Thanks a lot.


Solution

  • You're not writing anything to disk at any moment. If you're looking to modify the file, you should do it explicitly. You should find some pointers on how to hand Files in the official doc.