python读取txt,doc,md,html文件
时间: 2023-10-26 22:06:10 浏览: 41
你可以使用Python中的不同模块来读取不同类型的文件:
- 对于txt文件,你可以使用Python内置的 `open()` 函数来打开文件,然后使用 `read()` 或 `readlines()` 方法读取文件内容。
示例代码:
```python
with open('file.txt', 'r') as f:
content = f.read()
# 或者使用 f.readlines() 逐行读取文件内容
```
- 对于doc文件,你可以使用 `python-docx` 库来读取文件内容。
示例代码:
```python
import docx
doc = docx.Document('file.docx')
content = '\n'.join([para.text for para in doc.paragraphs])
```
- 对于html文件,你可以使用 `beautifulsoup4` 库来解析文件内容。
示例代码:
```python
from bs4 import BeautifulSoup
with open('file.html', 'r') as f:
soup = BeautifulSoup(f, 'html.parser')
content = soup.get_text()
```
- 对于md文件,你可以使用 `markdown` 或 `mistune` 等第三方库来解析文件内容。
示例代码:
```python
import markdown
with open('file.md', 'r') as f:
content = markdown.markdown(f.read())
```