python怎么读取文本文档
有四种方法可以使用 Python 读取文本文档:直接读取整个文件内容按行读取文件内容并存储在列表中逐行迭代文件内容指定文件的编码、读取模式和换行符等可选参数
如何使用 Python 读取文本文档
直接方法:
with open("filename.txt", "r") as f: contents = f.read()
按行读取:
with open("filename.txt", "r") as f: lines = f.readlines()
逐行迭代:
立即学习“Python免费学习笔记(深入)”;
with open("filename.txt", "r") as f: for line in f: # 对每一行进行操作
其他可选参数:
示例:
读取名为 "example.txt" 的文件并打印其内容:
with open("example.txt", "r") as f: contents = f.read()print(contents)
读取 "example.txt" 文件的每一行并将其存储在列表中:
with open("example.txt", "r") as f: lines = f.readlines()print(lines)
逐行读取 "example.txt" 文件并打印每一行:
with open("example.txt", "r") as f: for line in f: print(line)