python - 如何在替换和写入新文件时修复“AttributeError:'int'对象没有属性'replace'”?
问题描述
我有一个hello.py
文件询问用户他们的姓名并打印他们的欢迎信息。
import subprocess
filename = "hello-name.txt"
fout = open("out.txt", "w")
with open(filename, "r+") as f:
lines = f.readlines()
your_name = input("What is your name? ")
title_name = your_name.title()
for line in lines:
line = fout.write(line.replace("[Name]", your_name))
line = fout.write(line.replace("[Title]", title_name))
print(line.strip())
subprocess.call(["notepad.exe", "out.txt"])
这是我hello-name.txt
文件的内容
Hello [Name]
Welcome to the world [Title]
我的问题
运行时hello.py
,它会询问用户的姓名,一旦输入姓名,Python 就会给出以下错误:
line = fout.write(line.replace("[Title]", title_name))
AttributeError: 'int' object has no attribute 'replace'
请帮我解决这个问题。
谢谢你
解决方案
该write
方法返回写入的字符数,而不是写入的值。line
如果您想继续使用它,请不要将结果分配给它。如果目标是在写入之前执行两个替换,请同时执行它们,然后写入,例如:
for line in lines:
line = line.replace("[Name]", your_name)
line = line.replace("[Title]", title_name)
fout.write(line)
推荐阅读
- spring - 使用没有数据源的 Spring JPA 调用 Oracle 存储过程
- android - 如何在Delphi android中连接后(在监听模式下)使用蓝牙接收数据
- database - 将数据放在 Kafka 或数据库中?
- wordpress - 在wordpress中编辑帖子时如何设置指定的字体系列?
- php - `content_for_layout` 如何在 shopify 中加载内容?
- c# - 文件流重命名文件
- javascript - React Native - FlatList 对 renderItems 中的每个项目进行获取请求
- mongodb - 如何在 MongoDB 中应用密集排名?
- python - 如何根据另一个数据框中的变量从数据框中选择列
- python - 尝试在熊猫数据框中追加时获得“真”值而不是实际值