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.

JavaScript

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

JavaScript

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 :

JavaScript

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):

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement