如何将字符串写入文件中的任何特定(条件)位置

时间:2019-03-31 19:42:48

标签: python file

我写了这个python脚本来处理字典文件(这是一个文本文件),像这样:

单词在'#'之后,并且该单词的含义在\ n分隔的单词下。

...
#hello
xxx
yyy
zzz
#another
ooo

我想用这个python脚本在文件中添加单词。但是我不知道该怎么做。而最令人困惑的部分是,如果文件中包含该单词,则为其添加含义。

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

这是我可以在文件中添加单词及其含义的方法。我该怎么做。我写了许多脚本来完成,它们是:

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()

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)

0 个答案:

没有答案