简体   繁体   中英

Why does my .txt change format when I save it as another file?

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)

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:

  1. In general, use context managers ( with statements) with files -- these managers will automatically close files for you.
  2. 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'))

change this line

story = file.readlines()

with

story = file.read()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM