Skip to content
Advertisement

How to fix ” AttributeError: ‘int’ object has no attribute ‘replace’ ” while replacing and writing to a new file?

I have a hello.py file which asks user for their name and prints them a welcome message.

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"])

This is the content of my hello-name.txt file

Hello [Name]
Welcome to the world [Title]

My Question

When run hello.py it asks user for their Name and as soon as the name is entered, Python gives the following error :

line = fout.write(line.replace("[Title]", title_name))
AttributeError: 'int' object has no attribute 'replace'

Kindly help me to fix this issue.

Thank You

Advertisement

Answer

There are two problems with this script:

  1. As ShadowRanger pointed out, you’re assigning the result from write to line; this overwrites the content.
  2. You don’t close the output file before opening it in Notepad.

An easy way to make sure a file is closed is to open it in a context, using the with keyword. You already did this when you read the input file; just do the same thing for the output file, and open Notepad after the with block (i.e. after you’ve written both lines and closed the file):

import subprocess

with open("hello-name.txt", "r+") as f:
    lines = f.readlines()

your_name = input("What is your name? ")
title_name = your_name.title()

with open("out.txt", "w") as fout:
    for line in lines:
        line = line.replace("[Name]", your_name)
        line = line.replace("[Title]", title_name)
        fout.write(line)
        print(line.strip())

subprocess.call(["notepad.exe", "out.txt"])
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement