python 去除空行
时间: 2023-11-03 16:01:27 浏览: 87
您可以使用以下代码来去除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中的空行:
```
with open('file.txt') as f:
lines = f.readlines()
# 去除空行
lines = list(filter(lambda x: x.strip(), lines))
with open('file.txt', 'w') as f:
f.writelines(lines)
```
这段代码首先打开文件并读取每一行,然后使用`filter()`函数和`lambda`表达式从中过滤空行。最后,将过滤后的行重新写入文件中。
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)
```
这个函数将读取指定文件中的所有行,并将非空行重新写入同一文件中。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)