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)
這些方法都可以實現去除文件中的空行,選擇使用哪種方法取決于你的具體需求和個人偏好。