开发者

Python: line break in a textfile after specific word

开发者 https://www.devze.com 2023-04-01 02:58 出处:网络
I have a textfile and there\'s just one line with 10.000 words. Now I want to add a line break before a specific word (\"Comment\") appears and I also want to write 开发者_运维技巧this in a new textf

I have a textfile and there's just one line with 10.000 words. Now I want to add a line break before a specific word ("Comment") appears and I also want to write 开发者_运维技巧this in a new textfile:

The textfile looks like: "Comment: Yeah, you're right Comment: That's very interesting Comment: really?

And the new file should looks like:

    Comment: Yeah, you're right
    Comment: That's very interesting
    Comment: really?

I tried this code below but there's something wrong. I'm a beginner and until now, I wasn't able to find a solution. Thanks for your help

    -*- coding: utf-8 -*-

    d = file('test.txt','r')
    text=d.read()
    e = file('output.txt','w')
    x=raw_input("Insert word:")
    # -> Comment
    for line in d.readlines():
          if line.startswith(x):
            word.append(+"\n")
            e.write()
            e.close()
            d.close()


You just need to use str.replace:

e.write(d.read().replace(' Comment:', '\nComment:'))


Here are explanations of what's wrong, in order:

d = file('test.txt','r')
text=d.read() # Ok: now 'text' contains the entire file contents.
e = file('output.txt','w')
x=raw_input("Insert word:")
# -> Comment
for line in d.readlines(): # You already read the whole file, so
# this loop can't read any more. But even without that, your input
# file only contains one line, so this would only loop once.
      if line.startswith(x): # You are trying to look for a word at the
      # beginning of each line, in order to determine where to put the
      # line breaks. But the words can't be found at the beginnings of
      # all the lines until those lines exist, i.e. after the line 
      # breaks have been positioned.
        word.append(+"\n") # This makes no sense at all. You can't 
        # '.append' to 'word' because there is no 'word' defined yet,
        # and '+"\n"' is trying to treat a string like a number. Yes,
        # you can use '+' to join two strings, but then you need one
        # on either side of the '+'. 1 + 1, "hi " + "mom".
        e.write() # If you want to write something to the file, you have
        # to specify what should be written.
        e.close() # If the loop *did* actually execute multiple times,
        d.close() # then you definitely wouldn't want to close the files
        # until after the loop is done.

The other answers explain how to go about the problem correctly. We read the file into a string, and add a line break before each appearance of the word. This is equivalent to replacing each appearance of the word with (a line break, followed by the word). That functionality is built-in. Then we write the modified string to the output file.


A very simple solution could be:

for line in d.readlines():
    e.write(line.replace("Comment:",  "\nComment:"))

e.close()    


You could do '\n'.join(x+': '+string for string in line.split(x+': '))

0

精彩评论

暂无评论...
验证码 换一张
取 消