在Python中导入文本文件通常指的是读取文本文件的内容。以下是使用不同方法导入文本文件的示例:
1. 使用 `open()` 函数和 `with` 语句:
with open('file.txt', 'r') as file:content = file.read()print(content)
2. 使用 `pathlib` 模块读取文件路径和内容:
from pathlib import Pathfile_path = Path('file.txt')with file_path.open('r') as file:content = file.read()print(content)

3. 如果文本文件是Word文档(.docx格式),可以使用 `python-docx` 库:
import docxdef getText(filename):doc = docx.Document(filename)full_text = []for para in doc.paragraphs:full_text.append(para.text)return '\n'.join(full_text)if __name__ == '__main__':filename1 = r'/Users/fangluping/Desktop/数据分析笔试试题/长亮数据-咨询部笔试题目-附件/03.docx'text1 = getText(filename1)print(text1)
请根据你的需要选择合适的方法。
