Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python 读取文件内容

作者:你没有爱过我   发布日期:2025-12-15   浏览:43

# 示例代码:读取文件内容

# 使用 with 语句打开文件,确保文件在使用后正确关闭
with open('example.txt', 'r', encoding='utf-8') as file:
    # 读取文件的全部内容并存储在 content 变量中
    content = file.read()

# 打印文件内容
print(content)

解释说明:

  1. open() 函数:用于打开文件。参数 'example.txt' 是文件名,'r' 表示以只读模式打开文件,encoding='utf-8' 指定文件的编码格式为 UTF-8。
  2. with 语句:确保文件在使用后会正确关闭,即使发生异常也会自动关闭文件。
  3. file.read():读取文件的全部内容,并将其作为一个字符串返回。
  4. 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

大家都在看

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站