简体   繁体   中英

How to delete blank lines in a text file on a windows machine

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++

在此处输入图片说明

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

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 fe 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 

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM