Delete newline / return carriage in file output

后端 未结 6 1526
无人及你
无人及你 2020-12-16 16:55

I have a wordlist that contains returns to separate each new letter. Is there a way to programatically delete each of these returns using file I/O in Python?

Edit

6条回答
  •  臣服心动
    2020-12-16 17:30

    >>> string = "testing\n"
    >>> string
    'testing\n'
    >>> string = string[:-1]
    >>> string
    'testing'
    

    This basically says "chop off the last thing in the string" The : is the "slice" operator. It would be a good idea to read up on how it works as it is very useful.

    EDIT

    I just read your updated question. I think I understand now. You have a file, like this:

    aqua:test$ cat wordlist.txt 
    Testing
    
    This
    
    Wordlist
    
    With
    
    Returns
    
    Between
    
    Lines
    

    and you want to get rid of the empty lines. Instead of modifying the file while you're reading from it, create a new file that you can write the non-empty lines from the old file into, like so:

    # script    
    rf = open("wordlist.txt")
    wf = open("newwordlist.txt","w")
    for line in rf:
        newline = line.rstrip('\r\n')
        wf.write(newline)
        wf.write('\n')  # remove to leave out line breaks
    rf.close()
    wf.close()
    

    You should get:

    aqua:test$ cat newwordlist.txt 
    Testing
    This
    Wordlist
    With
    Returns
    Between
    Lines
    

    If you want something like

    TestingThisWordlistWithReturnsBetweenLines
    

    just comment out

    wf.write('\n')
    

提交回复
热议问题