美文网首页
Python 获取文件路径及遍历文件

Python 获取文件路径及遍历文件

作者: 崔某 | 来源:发表于2021-08-12 13:45 被阅读0次
# -*- coding: utf-8 -*-
# @Time    : 2021/8/10 17:58
# @File    : test_readfile.py

# 目录
import os

# 脚本路径
print(f"脚本文件路径:{os.path.realpath(__file__)}")

# 当前目录
print(f"当前目录:{os.path.dirname(os.path.realpath(__file__))}")
print(f"当前目录:{os.getcwd()}")


# 上级目录
print(f"上级目录:{os.path.abspath(os.path.join(os.getcwd(), '..'))}")
print(f"上级目录:{os.path.abspath(os.path.dirname(os.path.dirname(__file__)))}")
print(f"上级目录:{os.path.abspath(os.path.dirname(os.getcwd()))}")

# 上上级目录
print(f"上上级目录:{os.path.abspath(os.path.join(os.getcwd(), '../..'))}")

# 遍历文件名
for root, dirs, files in os.walk(os.getcwd()):
    for f in files:
        print(f)

print("======================分割线======================")

# 遍历文件路径
for root, dirs, files in os.walk(os.getcwd()):
    for f in files:
        print(os.path.join(root, f))


相关文章

网友评论

      本文标题:Python 获取文件路径及遍历文件

      本文链接:https://www.haomeiwen.com/subject/xhdlbltx.html