在Python中,去除文本文件中的空行可以通过多种方法实现,以下是几种常见的方法:
1. 使用`strip()`方法:
```python
with open('file.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
lines = [line.strip() for line in lines if line.strip()]
with open('cleaned_file.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)
2. 使用`rstrip()`方法:
```python
with open('file.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines if line.rstrip()]
with open('cleaned_file.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)
3. 使用`join()`方法:
```python
with open('file.txt', 'r', encoding='utf-8') as file:
content = file.read()
lines = [line for line in content.split('\n') if line.strip()]
result = '\n'.join(lines)
with open('cleaned_file.txt', 'w', encoding='utf-8') as file:
file.write(result)
4. 使用列表推导式:
```python
with open('file.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
non_empty_lines = [line for line in lines if line.strip()]
with open('cleaned_file.txt', 'w', encoding='utf-8') as file:
file.writelines(non_empty_lines)
以上代码示例中,``表示在列表推导式或生成器表达式过滤后,我们通常只保留非空行,因此使用切片``来排除掉空列表。
选择哪种方法取决于你的具体需求和个人偏好。