# 示例代码:读取文件内容
# 使用 with 语句打开文件,确保文件在使用后正确关闭
with open('example.txt', 'r', encoding='utf-8') as file:
# 读取文件的全部内容并存储在 content 变量中
content = file.read()
# 打印文件内容
print(content)
open() 函数:用于打开文件。参数 'example.txt' 是文件名,'r' 表示以只读模式打开文件,encoding='utf-8' 指定文件的编码格式为 UTF-8。with 语句:确保文件在使用后会正确关闭,即使发生异常也会自动关闭文件。file.read():读取文件的全部内容,并将其作为一个字符串返回。print(content):将读取到的内容打印出来。如果你需要逐行读取文件内容,可以使用 file.readlines() 或者直接遍历文件对象:
# 逐行读取文件内容
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip()) # strip() 去除每行末尾的换行符
上一篇:python __file__
下一篇:python的range
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站