Remove line breaks from a text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Chris9
    New Member
    • Mar 2010
    • 3

    Remove line breaks from a text file

    I have an ASCII table where each row is a line. I'd like to replace each line break with a space so that i end up with one very long row. Any ideas? Thanks!
  • zhaphod
    New Member
    • Mar 2010
    • 1

    #2
    Code:
    import re
    
    in_fd = open(in_fn, "r")
    
    file_lines = in_fd.readlines()
    
    out_fd = open(out_fn, "w")
    
    for lines in file_lines:
        new_line = re.sub("\n", "", lines)
        out_fd.write(new_line)
    
    out_fd.close()
    in_fd.close()
    Last edited by bvdet; Mar 3 '10, 03:15 PM. Reason: Add code tags

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      I prefer this non re solution.
      Code:
      fn1 = "text4.txt"
      fn2 = "text5.txt"
      
      f1 = open(fn1)
      f2 = open(fn2, 'w')
      outputList = [line.strip() for line in f1]
      f1.close()
      f2.write(" ".join(outputList))
      f2.close()

      Comment

      Working...