python获取当前路径

一、获取当前路径

      1、使用sys.argv[0]

import sys
print sys.argv[0]
#输出
#本地路径

      2、os模块

import  os
print os.getcwd() #获取当前工作目录路径
print os.path.abspath('.') #获取当前工作目录路径
print os.path.abspath('test.txt') #获取当前目录文件下的工作目录路径
print os.path.abspath('..') #获取当前工作的父目录 !注意是父目录路径
print os.path.abspath(os.curdir) #获取当前工作目录路径

    4、组合路径返回

         os.path.join('file1','file2','file3')

         合并得到路径 file1/file2/file3

>>> print os.path.join('E:', 'file1', 'file2')
E:/file1/file2
>>> print os.path.join('/home', '/home/file1/', '/home/file1/file2/')
/home/file1/file2/

        no.2

import os
root = os.getcwd()               #获得当前路径 /home/dir1
print root
#输出
#/home/dir1

name = "file1"                    #定义文件名字  
print(os.path.join(root, name))   #合并路径名字和文件名字,并打印
#输出
#/home/dir1/file1

二、获得当前目录下所有文件

      1. os.walk() 用于在目录树种游走输出目录中的文件名字,向上或下;

语法
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

参数: top -- 根目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径,
文件夹名字, 文件名】。 topdown --可选,为True或者没有指定, 一个目录的的3-元组将比它的任何子文件夹的3-元组先产生 (目录自上而下)。
如果topdown为 False, 一个目录的3-元组将比它的任何子文件夹的3-元组后产生 (目录自下而上)。 onerror -- 可选,是一个函数; 它调用时有一个参数, 一个OSError实例。报告这错误后,继续walk,或者抛出exception终止walk。 followlinks -- 设置为 true,则通过软链接访问目录。

 2.

import os
root = os.getcwd()

def file_name(file_dir):
    for root, dirs, files in os.walk(file_dir):
        print "-----------"
        print root   #os.walk()所在目录
        print dirs   #os.walk()所在目录的所有目录名
        print files   #os.walk()所在目录的所有非目录文件名
        print " "

file_name(root)

转载:https://www.cnblogs.com/Jomini/p/8636129.html

posted on 2019-06-24 14:46  灬菜鸟灬  阅读(77514)  评论(0编辑  收藏  举报

导航