import os.path
def add_text_to_file(self, filename, row_title, input_text):
# filename should have the .txt extension in it
filepath = os.path.join("check_files", filename)
with open(filepath, "r") as f:
content = f.readlines()
for j in len(content):
if row_title in content[j]:
content[j] = content[j].strip() + input_text + "\n"
break
with open(filepath, "w") as f:
f.writelines(content)
你没有给出太多的信息,所以即使我也不会使用下面的代码(因为我确信有更好的方法),它可能会帮助你解决问题。在
如果在开头找到您要搜索的文本,}。毕竟,它返回匹配开始时的索引。在
str.find
可能返回{所以你的情况应该是:
编辑:
上面的修正可以节省时间,但如果你用正确的方式,Python式的方式来处理,那就更好了。在
foo in bar
比较。如果foo
可以在bar
中找到,则为True
,否则为{enumerate
内置是您的朋友。在strip
或{a1}在您的情况下比替换要好。在with
语句。它将以正确的方式处理关闭文件。对于python2.5,您需要from __future__ import with_statement
以下是一个清理版本:
^{pr2}$相关问题 更多 >
编程相关推荐