#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    22
    Rep Power
    0

    How to replace space with newlines in many files


    Hi all...

    I want to replace space with newline in a huge number of files in a folder. For example, if the “file1.txt” contains “hello how are you”, after modifications the contents of the file1.txt should replaced with
    hello
    how
    are
    you


    and same for the other files (file2.txt, file3.txt)in the folder..
    any help? thanx
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    /dev/null
    Posts
    163
    Rep Power
    19
    Here's a sed one-liner for use on a linux command line:
    Code:
    sed -i.bak 's/ /\n/g' file*txt
    Do you specifically want a python script for this? (Curious, because you've posted this question in a python forum)

    Comments on this post

    • utpalmtbi agrees
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    618
    Rep Power
    65
    One way to do this ...
    Code:
    s = "hello how are you"
    
    s2 = s.replace(' ','\n')
    
    print(s)
    print('-'*20)
    print(s2)
    
    ''' result ...
    hello how are you
    --------------------
    hello
    how
    are
    you
    '''
    Applied to a file ...
    Code:
    ''' replace_space_newline.py
    assume file mydata.txt contains string
    hello how are you
    '''
    
    with open("mydata.txt") as fin, open("newdata.txt", "w") as fout:
        s = fin.read()
        s2 = s.replace(' ','\n')
        fout.write(s2)
    
    # testing
    print(s)
    print(s2)

    Comments on this post

    • utpalmtbi agrees
    Last edited by Dietrich; June 13th, 2013 at 05:59 PM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo