# 示例代码:读取文件路径
# 导入os模块,用于处理文件和目录路径
import os
# 定义一个函数来读取文件内容
def read_file(file_path):
try:
# 检查文件是否存在
if os.path.exists(file_path):
# 以只读模式打开文件
with open(file_path, 'r', encoding='utf-8') as file:
# 读取文件内容并返回
content = file.read()
return content
else:
return "文件不存在"
except Exception as e:
return f"读取文件时发生错误: {e}"
# 示例文件路径
file_path = 'example.txt'
# 调用函数并打印结果
print(read_file(file_path))
os
模块来检查文件是否存在。read_file
函数接收一个文件路径作为参数。os.path.exists()
检查文件是否存在。with open()
语句以只读模式 ('r'
) 打开文件,并指定编码为 utf-8
。file.read()
读取文件的全部内容。example.txt
并调用 read_file
函数读取其内容。下一篇:python时间格式
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站