首页 > 解决方案 > 如何将字符串写入文件上的任何特定(条件)位置

问题描述

我编写了这个 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)

标签: pythonfile

解决方案


推荐阅读