Python中去除空行的方法有多种,以下是其中几种常见的方法:
with open('file.txt', 'r') as file:
lines = file.readlines()
lines = [line.strip() for line in lines if line.strip()]
with open('file.txt', 'r') as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines if line.rstrip()]
with open('file.txt', 'r') as file:
content = file.read()
lines = [line for line in content.split('\n') if line.strip()]
result = '\n'.join(lines)
这些方法都可以实现去除文件中的空行,选择使用哪种方法取决于你的具体需求和个人偏好。