How to delete all blank lines in the file with the help of python?
import fileinput
for line in fileinput.FileInput("file",inplace=1):
if line.rstrip():
print line
Delete blank/empty lines in text file for Python
If you want to remove blank lines from an existing file without writing to a new one, you can open the same file again in read-write mode (denoted by 'r+'
) for writing. Truncate the file at the write position after the writing is done:
with open('file.txt') as reader, open('file.txt', 'r+') as writer:
for line in reader:
if line.strip():
writer.write(line)
writer.truncate()
Demo: https://repl.it/@blhsing/KaleidoscopicDarkredPhp
How to delete empty lines from a .txt file
This is how I would do it:
with open('path/to/file') as infile, open('output.txt', 'w') as outfile:
for line in infile:
if not line.strip(): continue # skip the empty line
outfile.write(line) # non-empty line. Write it to output
Strip blank lines from a text file
So firstly, the output is appended to the file because you open the file in r+
mode and the file pointer is pointing at the end of the file. You won't want to overwrite the file while you're reading it, though, so you really need two files:
with open('infile.txt', 'r', encoding='utf-8') as inFile,\
open('outfile.txt', 'w', encoding='utf-8') as outFile:
for line in inFile:
if line.strip():
outFile.write(line)
one liner for removing blank lines from a file in python?
lines = [i for i in open(file_path) if i[:-1]]
If writing to another file is a requirement, you can use file_object.writelines(lines)
with opening file for writing.
How to eliminate blank lines from a file
def elimina_client(self):
with open("clienti.txt","r") as f:
lines=f.readlines()
with open("clienti.txt","w") as f:
[f.write(line) for line in lines if line.strip() ]
Python3 with iterators:
#!/usr/bin/env python3
def elimina(fsrc, fdst):
with open(fsrc,'r') as src, open(fdst,'w') as dst:
[ dst.writelines(line) for line in src if line.strip() ]
if __name__ == '__main__':
elimina('text.txt','text_out.txt')
How to delete blank lines from CSV file?
You don't have a CSV file, so don't try to treat it as one. CSV specifically means a file consisting of rows of columns, where all rows have the same number of columns and the columns are delimited by a single character (usually a comma or a tab).
There is no need to delete the lines from your source file if all you needed was those first 4 values for your code either.
Just loop over the lines in the file, split each line by whitespace, and if the resulting list is not empty, take the last value:
numbers = []
with open(filename) as inf:
for line in inf:
data = line.split()
if data:
numbers.append(data[-1])
str.split()
with no arguments splits on arbitrary length whitespace, including tabs, spaces and newlines, with any whitespace at the start and end ignored.
When a line is empty the line
string will be '\n'
, and splitting such a line results in an empty list. If there is anything other than whitespace on a line, you get a list of strings for each non-whitespace section:
>>> '\n'.split()
[]
>>> 'P Inst Usage (Bytes): 13322\n'.split()
['P', 'Inst', 'Usage', '(Bytes):', '13322']
Because your file has the numbers you want at the end of each line, taking the last element (with [-1]
) gets you all the numbers.
If you only need the top four such lines, test the len(numbers)
result:
numbers = []
with open(filename) as inf:
for line in inf:
data = line.split()
if data:
numbers.append(data[-1])
if len(numbers) == 4:
break
The break
stops the for
loop, and when you exit the with
statement, the file will be closed automatically.
If you do ever need to skip blank lines, just test if line.strip()
is truthy; str.strip()
uses the same arbitrary-width whitespace rules to remove whitespace from the start and end. Empty lines with just a newline separator end up as empty strings, which are considered false when used in a boolean test such as an if ...:
condition:
if line.strip():
# line is not empty
You could then write that to a new file if you so wish, but that's not really needed here.
How to remove empty lines with or without whitespace in Python
Using regex:
if re.match(r'^\s*$', line):
# line is empty (has only the following: \t\n\r and whitespace)
Using regex + filter()
:
filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
As seen on codepad.
Related Topics
How to Handle a Broken Pipe (Sigpipe) in Python
Plotting 3D Polygons in Python-Matplotlib
How to Fix "Importerror: No Module Named ..." Error in Python
Elegant Way to Check If a Nested Key Exists in a Dict
Pandas Create New Column with Count from Groupby
How to Get the Nth Element of a Python List or a Default If Not Available
How to Request a Url in Python and Not Follow Redirects
Why Does Defining _Getitem_ on a Class Make It Iterable in Python
Download Image with Selenium Python
Python Extending with - Using Super() Python 3 VS Python 2
What Is the Most Efficient Way to Get First and Last Line of a Text File
How to Select Python Version in Pycharm
Extract Number from String in Python
In Django - Model Inheritance - Does It Allow You to Override a Parent Model's Attribute
Get Previous Row's Value and Calculate New Column Pandas Python