3

I am trying to delete all blank lines in all YAML files in a folder. I have multiple lines with nothing but CRLF (using Notepad++), and I can't seem to eliminate these blank lines. I researched this before posting, as always, but I can't seem to get this working.

import glob
import re
path = 'C:\\Users\\ryans\\OneDrive\\Desktop\\output\\*.yaml'

for fname in glob.glob(path):
    with open(fname, 'r') as f:
        sfile = f.read()
        for line in sfile.splitlines(True):
            line = sfile.rstrip('\r\n')
            f = open(fname,'w')
            f.write(line)
            f.close()

Here is a view in Notepad++

enter image description here

I want to delete the very first row shown here, as well as all other blank rows. Thanks.

ASH
  • 20,759
  • 19
  • 87
  • 200
  • 1
    I am afraid that you cannot read and write to the same file at the same time without using seek(). Usually the better way is to create a temporary file, write the change there and then replace the original one (or rename the original to .backup or something). That way if the program fails in the middle you still have a consistent state. Otherwise it should be enough to add `if line != '':` after the `rstrip()`. So you really skip the empty lines. – petrch Nov 21 '18 at 15:34

3 Answers3

0

You cant write the file you are currently reading in. Also you are stripping things via file.splitlines() from each line - this way you'll remove all \r\n - not only those in empty lines. Store content in a new name and delete/rename the file afterwards:

Create demo file:

with open ("t.txt","w") as f:
    f.write("""

asdfb 

adsfoine 

""")

Load / create new file from it:

with open("t.txt", 'r') as r, open("q.txt","w") as w:
    for l in r:
        if l.strip(): # only write line if when stripped it is not empty
            w.write(l)

with open ("q.txt","r") as f:
   print(f.read())  

Output:

asdfb 
adsfoine 

( You need to strip() lines to see if they contain spaces and a newline. )

For rename/delete see f.e. How to rename a file using Python and Delete a file or folder

import os
os.remove("t.txt")               # remove original
os.rename("q.txt","t.txt")       # rename cleaned one
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

If you use python, you can update the line using:

re.sub(r'[\s\r\n]','',line)

Close the reading file handler before writing.

If you use Notepad++, install the plugin called TextFX.

  1. Replace all occurances of \r\n with blank.
  2. Select all the text
  3. Use the new menu TextFX -> TextFX Edit -> E:Delete Blank Lines

I hope this helps.

pratik mankar
  • 126
  • 1
  • 10
0

It's nice and easy...

file_path = "C:\\Users\\ryans\\OneDrive\\Desktop\\output\\*.yaml"

with open(file_path,"r+") as file:
    lines = file.readlines()
    file.seek(0)
    for i in lines:
        if i.rstrip():
            file.write(i)

Where you open the file, read the lines, and if they're not blank write them back out again.