python - 函数不写入文本文件
问题描述
我正在尝试在文本文件中制作一种日志以避免重复工作。我有以下执行此任务的功能:
def write_to_logbook(target_name):
with open('C:\Documents\logbook.txt', 'a+') as f:
for lines in f:
if target_name not in lines:
f.write(target_name + '\n')
f.close() #when I didn't have f.close() here, it also wasn't writing to the txt file
当我在运行脚本后检查文本文件时,它仍然是空的。我不确定为什么。
我这样称呼它(实际上目标名称是从唯一 ID 中提取的,但由于我不想将所有内容都放在这里,所以这是要点):
target_name = 'abc123'
write_to_logbook(target_name)
解决方案
您需要(可能)阅读整个文件,然后才能决定是否target_name
必须将其添加到文件中。
def write_to_logbook(target_name):
fname = r'C:\Documents\logbook.txt')
with open(fname) as f:
if any(target_name in line for line in f):
return
with open(fname, 'a') as f:
print(target_name, file=f)
any
将在找到True
任何包含target_name
的行后立即返回,此时函数本身将返回。
如果读取整个文件后没有找到目标名称,则第二with
条语句会将目标名称附加到文件中。
推荐阅读
- reactjs - 打字稿不正确的空/从不检查反应参考
- javascript - 在 Ant Design 中的 Step 中嵌套下拉菜单
- ios - 当我点击 UIImagePicker galary 的图像按钮以在 iPad 中选择图像时,应用程序崩溃了,为什么?
- wordpress - 通过 WooCommerce 回调更新 WooCommerce 订单状态
- mongodb - Mongoose:始终如一地保存文档顺序
- amazon-web-services - 发布端口时,Swarm 中的 Docker 服务无法连接到 AWS RDS
- jupyter-notebook - 依次调用多个 Jupyter Notebook
- c++ - 在 VisualStudio 程序中输入 cin 参数
- css - 使用 tailwind @apply 函数的 Angular 组件特定样式
- java - 将数组中的变量添加到另一个数组中