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

python读取文件路径怎么写

作者:伱的精力病康复了?   发布日期:2026-06-05   浏览:67

# 示例代码:读取文件路径

# 假设我们有一个文本文件 'example.txt',我们想要读取它的内容。

# 方法1:使用绝对路径
# 绝对路径是从根目录开始的完整路径。
file_path = r"C:\Users\YourUsername\Documents\example.txt"  # Windows系统下的绝对路径
# file_path = "/home/yourusername/Documents/example.txt"  # Linux或Mac系统下的绝对路径

with open(file_path, 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

# 方法2:使用相对路径
# 相对路径是相对于当前工作目录的路径。
# 如果 'example.txt' 在与 Python 脚本相同的目录中,可以直接使用文件名。
file_path = "example.txt"

with open(file_path, 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

解释说明:

  1. 绝对路径:从根目录开始,指定文件的完整路径。适用于文件位置固定的情况。
  2. 相对路径:相对于当前工作目录的路径。如果文件和脚本在同一目录下,可以直接使用文件名。
  3. with open():使用 with 语句打开文件可以确保文件在使用后自动关闭。
  4. encoding='utf-8':指定文件的编码格式,避免读取时出现编码问题。

希望这些示例能帮助你理解如何在 Python 中读取文件路径。

上一篇:python fire

下一篇:python读取word

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python的assert基本用法

python开发windows应用程序

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

Laravel 中文站