I have a hello.py
file which asks user for their name and prints them a welcome message.
JavaScript
x
19
19
1
import subprocess
2
3
filename = "hello-name.txt"
4
5
fout = open("out.txt", "w")
6
7
with open(filename, "r+") as f:
8
lines = f.readlines()
9
10
your_name = input("What is your name? ")
11
title_name = your_name.title()
12
13
for line in lines:
14
line = fout.write(line.replace("[Name]", your_name))
15
line = fout.write(line.replace("[Title]", title_name))
16
print(line.strip())
17
18
subprocess.call(["notepad.exe", "out.txt"])
19
This is the content of my hello-name.txt
file
JavaScript
1
3
1
Hello [Name]
2
Welcome to the world [Title]
3
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
1
3
1
line = fout.write(line.replace("[Title]", title_name))
2
AttributeError: 'int' object has no attribute 'replace'
3
Kindly help me to fix this issue.
Thank You
Advertisement
Answer
There are two problems with this script:
- As ShadowRanger pointed out, you’re assigning the result from
write
toline
; this overwrites the content. - 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
1
17
17
1
import subprocess
2
3
with open("hello-name.txt", "r+") as f:
4
lines = f.readlines()
5
6
your_name = input("What is your name? ")
7
title_name = your_name.title()
8
9
with open("out.txt", "w") as fout:
10
for line in lines:
11
line = line.replace("[Name]", your_name)
12
line = line.replace("[Title]", title_name)
13
fout.write(line)
14
print(line.strip())
15
16
subprocess.call(["notepad.exe", "out.txt"])
17