Jomini

一、获取当前路径

 

      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) #获取当前工作目录路径

 

 

    3、改变当前目录

         1) 使用: os.chdir(path)。

         比如, 如果当前目录在 ‘E:’ 下面, 然后进入E 下面的files 文件 可以使用 os.chdir(E:\files).

         之后,使用比如 test1 = open(\'file1.txt\'),  打开的文件会是在这个 ‘E:\files’ 目录下的文件,而不是 \'E\' 下的文件。

   

    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)

  -----------  ---------- ----谢谢大佬打赏     --------  --------  --------

 

 

 

转载源头:

     [1]:   Purple_dandelion 

      https://blog.csdn.net/qq_15188017/article/details/53991216

分类:

技术点:

相关文章:

  • 2021-11-23
  • 2021-12-22
  • 2021-11-29
  • 2021-11-23
  • 2021-12-08
  • 2022-01-25
  • 2021-12-23
猜你喜欢
  • 2022-01-29
  • 2022-01-15
  • 2021-11-23
  • 2021-12-20
  • 2021-12-26
相关资源
相似解决方案