0

I wrote this python script for handling dictionary file (which is a text file) like this:

Word goes after the '#' and the meanings of that word goes under the word seperated by \n.

...
#hello
xxx
yyy
zzz
#another
ooo

I'want to add words to file with this python script. But I don't know how to do that. And most confusing part is if the file has that word then add meanings to it.

./main.py add 'hello' 'xxx;yyy;zzz;'

This is how I can add the word and it's meanings to the file. How could I do that. I wrote many scripts to accomplish and they're:

def add(d,w,m):
    dic = dictPath+d
    nwords = '\n'.join(m.split(";"))
    wmean = '#'+w+'\n'+nwords
    here = False
    lnum=0
    with open(dic,"r") as rf:
        for line in rf:
            if line == "#"+w+"\n": ## 'cause every line ends with \n
                here="yes"
                lnum+=1
            else:
                lnum+=1
    if here == "no":
        with open(dic,"a") as af:
            af.writelines(wmean)
    else:
        with open(dic,"w") as wf:
            data = rf.readlines()
            data[lnum+1] = nwords
            wf.writelines(data)
        wf.close()
        rf.close()
        af.close()

and

def add(d,w,m):
    dic = dictPath+d
    nwords = '\n'.join(m.split(";"))
    wmean = '#'+w+'\n'+nwords
    with open(dic,"r+") as f:
        for line in f:
            if line == "#"+w+"\n":
                f.write(wmean)
  • 1
    Why this (rather convoluted) format? You would get better mileage (and much simpler code) out of using a conventional format like JSON or CSV. – rdas Mar 31 '19 at 19:47
  • The best way to add items to such file is to read all of it to a structure, then add to the structure, then **write everything** back into the file. – zvone Mar 31 '19 at 19:48
  • I wanted to learn file handling. That's why i chosed this way. –  Mar 31 '19 at 19:49
  • @zvone but it's using more ram, right? I don't wanna use that. –  Mar 31 '19 at 19:50
  • Read about [Random_access](https://en.wikipedia.org/wiki/Random_access) and [python-random-access-file](https://stackoverflow.com/questions/4999340/python-random-access-file) – stovfl Mar 31 '19 at 20:05
  • These are English words. There cannot be more than a few thousand of them, even if you listed all of them. Each could be 10 bytes long on average. So, we're talking about < 100 kB RAM. You probably have gigabytes available. So, yes, you do want to spend 100 kB RAM rather than complicate your code. – zvone Mar 31 '19 at 20:47

0 Answers0