简体   繁体   中英

How to remove empty lines depending on certain conditions in a txt file?

input_file_1.txt




Python is a high-level, general-purpose programming language


This book is an introduction to programming in Oracle’s Java™ programming language
An object is composed of fields and methods

A shell is a command-line interpreter and typical operations performed by shell scripts include file manipulation, program execution, and printing text.




I also have other files called input_file_2.txt and input_file_3.txt , and they both have the same content as input_file_1.txt .

For the file input_file_1.txt I need to read it and remove all the possible empty lines that are at the beginning, except one.

input_file_1.txt


Python is a high-level, general-purpose programming language


This book is an introduction to programming in Oracle’s Java™ programming language
An object is composed of fields and methods

A shell is a command-line interpreter and typical operations performed by shell scripts include file manipulation, program execution, and printing text.




For the file input_file_2.txt I need to read it and remove all the possible empty lines that are at the end, except one

input_file_2.txt




Python is a high-level, general-purpose programming language


This book is an introduction to programming in Oracle’s Java™ programming language
An object is composed of fields and methods

A shell is a command-line interpreter and typical operations performed by shell scripts include file manipulation, program execution, and printing text.

And for the input_file_3.txt file I need to read it and delete those empty lines that are in the middle of 2 non-empty lines.

input_file_3.txt




Python is a high-level, general-purpose programming language
This book is an introduction to programming in Oracle’s Java™ programming language
An object is composed of fields and methods
A shell is a command-line interpreter and typical operations performed by shell scripts include file manipulation, program execution, and printing text.




How should I correctly read each of these 3 files that are initially the same but then I will modify each one so that they meet the conditions of each of these 3 cases?

You can look at any doccumentation online. There are many websites, such as this one https://datagy.io/python-read-text-file/ which I just googled, that will help you achieve what you're trying to do.

You can also just check whether certain lines are empty or only contain '\n' and skip over those lines.

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