首页 > 解决方案 > 如何在替换和写入新文件时修复“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'

请帮我解决这个问题。

谢谢你

标签: python

解决方案


write方法返回写入的字符数,而不是写入的值。line如果您想继续使用它,请不要将结果分配给它。如果目标是在写入之前执行两个替换,请同时执行它们,然后写入,例如:

for line in lines:
    line = line.replace("[Name]", your_name)
    line = line.replace("[Title]", title_name)
    fout.write(line)

推荐阅读