python - 如何将字符串写入文件上的任何特定(条件)位置
问题描述
我编写了这个 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)
解决方案
推荐阅读
- google-sheets - 如何快速创建工作表的超链接
- tcl - 如何匹配字符串并在此之后打印下一个单词?
- html - CSS光标图像奇怪的问题
- joomla - 无法从浏览器访问具有静态 IP 地址的 htdocs
- java - 有哪些选项可以导出更改了速度和音高的音频文件?
- javascript - 如果数组包含具有特定 id 的对象,则返回 true
- c# - EntityFramework Core 是否支持实体的 Eager Loading?
- reactjs - React:高效的重新渲染表格
- python - Python 和指南针数据 - 算法?
- ios - 如何使用 iOS 的 WKWebView 的 callAsyncJavaScript 方法?