3、读取文档内容,显示除了星号(*)开头的行以外的所有行。
时间: 2024-05-07 22:16:34 浏览: 18
可以使用Python语言读取文档内容,并使用循环遍历每一行,判断该行是否以星号(*)开头,如果不是,则将该行输出。以下是示例代码:
```
with open('document.txt', 'r', encoding='utf-8') as f:
for line in f:
if not line.startswith('*'):
print(line.strip())
```
其中,`document.txt`是要读取的文档文件名,`strip()`方法用于去除每一行结尾的换行符。
相关问题
python读取文档内容,显示除了星号开头的行以外所有行
可以使用Python的文件操作和字符串处理来实现读取文档内容并显示除了星号开头的行以外的所有行。以下是一个简单的实现示例:
```python
with open('filename.txt', 'r') as f:
for line in f:
if not line.startswith('*'):
print(line.strip())
```
其中,`filename.txt` 是要读取的文档文件名;`with open('filename.txt', 'r') as f:` 是打开文件并创建一个文件对象 `f`; `for line in f:` 是遍历文件对象中的每一行;`if not line.startswith('*'):` 是判断行是否以星号开头,如果不是,则 `print(line.strip())` 打印该行内容(去掉行末的换行符)。
注意,这个实现假设每行开头的空格是可以忽略的。如果需要考虑空格,可以使用 `line.lstrip()` 去掉行首空格后再进行判断。
python读取文档内容,显示除了星号(*)开头的行以外的所有行
可以使用Python的文件读取操作,读取文档的每一行,然后判断每一行是否以星号(*)开头,如果不是,则打印出来。示例代码如下:
```python
with open('filename.txt', 'r') as f:
for line in f:
if not line.startswith('*'):
print(line.strip())
```
其中,`filename.txt` 是要读取的文档文件名。`with open()` 语句可以打开文件,并在处理完毕后自动关闭文件。`for line in f` 语句可以遍历文件中的每一行。`line.startswith('*')` 可以判断当前行是否以星号(*)开头。`print(line.strip())` 可以打印出当前行(去掉换行符)。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)