Why does my code not save as the original text? Please explain. This question has been answered by the upmost voted person thank you for you suggestions.
Here is my code:
import re
#where I opened the file
file = open("old.txt")
story = file.readlines()
#Attempt to save file under new name with same format as orginal.
new = open('anotherstory.txt' , 'w')
new.write()
new.close()
# Made the substitution for the name
name = 'heatherly'
subname = 'joe'
nameCount = re.findall(name)
found = re.replace(name, subname)
CodePudding user response:
You're operating on the string representation of a list when you use str(story)
, since .readlines()
returns a list of strings.
The quick fix is to replace .readlines()
with .read()
(to get the contents of the file in one contiguous string rather than a list of strings that each represent one line).
That being said, I think we can do better. There's two unnecessary complexities that you can eliminate here:
- In general, use context managers (
with
statements) with files -- these managers will automatically close files for you. - You don't need a regular expression: a simple string
.replace()
operation will do here.
With this, we get:
with open("story.txt") as input_file, open("anotherstory.txt", "w") as output_file:
for line in input_file:
output_file.write(line.replace('heatherly', 'joe'))
CodePudding user response:
change this line
story = file.readlines()
with
story = file.read()
CodePudding user response:
str(story)
formats the list of lines as
['line1', 'line2', 'line3', ...]`
This is not the format you want in the file.
You should read the file as a single string, not a list of lines. Then you don't need to call str(story)
.
There's also no need to use re.sub()
, since name
is not a regular expression.
#where I opened the file
with open("story.txt") as file:
story = file.read()
# Made the substitution for the name
name = 'heatherly'
subname = 'joe'
nameCount = story.count(name)
found = story.replace(name, subname)
#Attempt to save file under new name with same format as orginal.
with open('anotherstory.txt' , 'w') as new:
new.write(found)