python中实现删除文本中的空行
时间: 2024-05-13 07:18:16 浏览: 17
可以使用以下代码删除文本中的空行:
```python
with open('file.txt', 'r') as f:
lines = f.readlines()
# 删除空行
lines = [line for line in lines if line.strip()]
with open('new_file.txt', 'w') as f:
f.write(''.join(lines))
```
首先,使用`readlines()`函数读取文件中的所有行,存储在一个列表中。然后,使用列表推导式过滤掉空行(使用`strip()`函数判断是否为空行),将不为空的行存储在一个新的列表中。
最后,使用`write()`函数将过滤后的行写入一个新文件中。
相关问题
删除文本中的空行 python
可以使用Python中的字符串操作来删除文本中的空行。以下是一个简单的示例:
```python
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:
for line in infile:
if line.strip(): # 如果不是空行
outfile.write(line)
```
这个代码块打开一个名为“input.txt”的文件,然后创建一个名为“output.txt”的文件以写入非空行。对于输入文件中的每一行,使用`strip()`方法去除行尾的空格和换行符,如果行不为空,则将其写入输出文件中。
python删除文件中所有空行
可以使用以下代码来删除文本文件中的所有空行:
```python
with open('input.txt', 'r') as input_file:
with open('output.txt', 'w') as output_file:
for line in input_file:
if line.strip(): # 如果该行不是空行
output_file.write(line)
```
在上面的代码中,我们打开输入文件 `input.txt` 以及输出文件 `output.txt`,然后遍历每一行。如果该行不是空行,则将其写入输出文件中。注意,我们使用 `line.strip()` 来判断该行是否为空行,这会移除行首和行尾的空格、制表符等空白字符。
如果你想直接修改原始文件,可以使用以下代码:
```python
with open('input.txt', 'r+') as file:
lines = file.readlines()
file.seek(0)
file.truncate() # 清空文件内容
for line in lines:
if line.strip(): # 如果该行不是空行
file.write(line)
```
在上面的代码中,我们打开文件 `input.txt`,读取所有行并保存到 `lines` 列表中。然后,我们使用 `file.seek(0)` 将文件指针移动到文件开头,使用 `file.truncate()` 清空文件内容。最后,我们遍历 `lines` 列表,将非空行写入文件中。注意,我们使用 `r+` 模式打开文件,这允许我们同时读取和写入文件。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)