python怎么去除空行
时间: 2024-01-10 07:45:40 浏览: 20
可以使用以下代码去除空行:
```python
with open('file.txt', 'r') as f:
lines = f.readlines()
# 去除空行
non_empty_lines = [line.strip() for line in lines if line.strip()]
# 将结果写回到文件中
with open('file.txt', 'w') as f:
f.write('\n'.join(non_empty_lines))
```
以上代码先读取文件中的所有行,然后使用列表推导式去除空行。最后将结果写回到文件中。
相关问题
python 去除空行
您可以使用以下代码来去除Python中的空行:
```python
def remove_empty_lines(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
non_empty_lines = [line for line in lines if line.strip()]
with open(file_path, 'w') as file:
file.writelines(non_empty_lines)
```
此代码将读取指定文件的内容,并删除其中的空行。它使用了列表推导式来过滤掉只包含空格或制表符的行,然后将结果重新写回原文件。
python 去除 空行
要去除Python中的空行,你可以使用以下代码:
```python
def remove_empty_lines(filename):
with open(filename, 'r') as file:
lines = file.readlines()
with open(filename, 'w') as file:
for line in lines:
if line.strip():
file.write(line)
```
这个函数将读取指定文件中的所有行,并将非空行重新写入同一文件中。