简体   繁体   中英

Reading and writing a file in python

Im trying to read a file line by line. I want to replace key with value if found in the dictionary and write the contents to the new file. Here is the logic:

fout = open(output_file,"w+")

with open(input_file, 'r') as fin:
    for line in fin:
        for key in sorted(Db):
            if re.match(key,line):
                line = re.sub(key,Db[key],line) ## line 246 
                fout.write(line)
                break
            else:
                fout.write(line)

Whenever i try to run this file, I'm getting the following tracebacks:

Traceback (most recent call last):
  File "final.py", line 246, in <module>
    if re.match(key,line):
  File "c:\Python33\lib\re.py", line 156, in match
    return _compile(pattern, flags).match(string)
  File "c:\Python33\lib\functools.py", line 258, in wrapper
    result = user_function(*args, **kwds)
  File "c:\Python33\lib\re.py", line 274, in _compile
    return sre_compile.compile(pattern, flags)
  File "c:\Python33\lib\sre_compile.py", line 493, in compile
    p = sre_parse.parse(p, flags)
  File "c:\Python33\lib\sre_parse.py", line 724, in parse
    p = _parse_sub(source, pattern, 0)
  File "c:\Python33\lib\sre_parse.py", line 347, in _parse_sub
    itemsappend(_parse(source, state))
  File "c:\Python33\lib\sre_parse.py", line 552, in _parse
    raise error("nothing to repeat")
sre_constants.error: nothing to repeat

Kindly let me know if I'm missing something. Thanks in advance.

Thanks, Anand

I think you should try and debug this problem yourself. Here is what I would do. add a print statement in your script before line 246:

print key, 
print Db[key]
print line

Depending on the output, take action. To test what would work, you can use the python interpreter. Assuming you get out of the print above:

key
foo
key 123

you can test it:

line = 'key 123'
re.sub('key', 'foo', line)
'foo 123'

In this case it works. I'm sure you'll soon find out what the problem is. Good luck!

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