用python读取文件,将文件中的空行和每一行的空格都删去后保存到另一个文件
时间: 2024-02-23 08:01:58 浏览: 26
可以使用 Python 的文件操作和字符串操作来实现,将处理后的文本保存到另一个文件中。
代码示例:
```python
with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:
lines = input_file.readlines()
for line in lines:
line = line.strip()
if line:
line = line.replace(' ', '') # 删除空格
output_file.write(line + '\n') # 写入新的文件,每行末尾添加换行符
```
上述代码首先使用 `with open()` 语句打开输入文件和输出文件,并逐行读取输入文件内容。然后使用 `strip()` 函数去除每一行末尾的空白字符,判断该行是否为空行。如果该行不为空行,则使用 `replace()` 函数删除该行中的空格。最后,将处理后的每一行写入输出文件中,每行末尾添加换行符。
注意:上述代码中的 `input.txt` 和 `output.txt` 需要替换成实际文件的名称或路径。
相关问题
用python读取文件,将文件中的空行和每一行的空格都删去
可以使用 Python 的文件操作和字符串操作来实现。
首先,使用 `open()` 函数打开要读取的文件,然后逐行读取文件内容。针对每一行,使用 `strip()` 函数去除行末的空白字符(包括空格、制表符和换行符),然后判断该行是否为空行。如果该行不是空行,则将其添加到一个新的字符串列表中。
代码示例:
```python
with open('filename.txt', 'r') as file:
lines = file.readlines()
new_lines = []
for line in lines:
line = line.strip()
if line:
new_lines.append(line)
# 打印去除空行和空格后的结果
for line in new_lines:
print(line)
```
上述代码首先使用 `with open()` 语句打开文件并读取所有行,然后使用 `strip()` 函数去除每一行末尾的空白字符。如果该行不为空行,则将其添加到一个新的字符串列表中。最后,遍历新的字符串列表并打印每一行的内容。
注意:上述代码中的 `filename.txt` 需要替换成实际文件的名称或路径。
python读取文件后将读出的每句的首单词依次写入到另一个文件中,程序保存在目录下
好的,以下是 Python 的代码实现:
```python
# 打开要读取的文件
with open('input.txt', 'r') as f:
# 读取文件中的所有行
lines = f.readlines()
# 打开要写入的文件
with open('output.txt', 'w') as f:
# 遍历每一行
for line in lines:
# 将每一行按空格分隔成单词列表
words = line.split()
# 取出每句的首单词并写入到输出文件中
f.write(words[0] + '\n')
```
这个程序会将 `input.txt` 文件中每一句话的首单词依次写入到 `output.txt` 文件中,并保存在程序所在的目录下。注意,如果 `input.txt` 文件中有空行,则程序会在输出文件中写入一个空行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)