python 文件|路径 常用方法

1、从字符串中获取文件路径

>>> import os
>>> existGDBPath = r'T:DataDBDesignDBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:DataDBDesign'

2、处理文件路径相关

In [1]: from pathlib import Path  # 首先导入Path

In [2]: current_path = Path(".")  # 获取当前路径

In [3]: current_path.home()  # 打印家目录的路径
Out[3]: PosixPath('/home/jiajun')

In [4]: current_path.resolve()  # 获取绝对路径
Out[4]: PosixPath('/home/jiajun/Code/blog')

In [5]: current_path.glob("*.py")  # 使用glob来匹配文件或者文件夹
Out[5]: <generator object Path.glob at 0x7f88b533a840>

In [6]: [i for i in current_path.glob("*.py")]
Out[6]:
[PosixPath('config.py'),
 PosixPath('gen_catalog.py'),
 PosixPath('utils.py'),
 PosixPath('models.py')]

In [7]: fake_path = current_path / "helloworld"  # 使用 / 来增加层级,是不是比 os.path.join 好看些

In [8]: fake_path.resolve()
Out[8]: PosixPath('/home/jiajun/Code/blog/helloworld')

In [9]: fake_path.exists()  # 判断是否存在
Out[9]: False

3、

import os

os.chdir("目标目录")   #修改当前工作目录

os.getcwd()    #获取当前工作目录

4、判断命令执行成功

if os.system('lss')  !=0:
    print 'Without the command'

5、去除空格

 "   xyz   ".strip()            # returns "xyz"

 "   xyz   ".lstrip()           # returns "xyz   "

 "   xyz   ".rstrip()           # returns "   xyz"

 "  x y z  ".replace(' ', '')   # returns "xyz"

6、去除换行符

replace("
", "")

7、目录

import os

print '***获取当前目录***'
print os.getcwd()
print os.path.abspath(os.path.dirname(__file__))

print '***获取上级目录***'
print os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
print os.path.abspath(os.path.dirname(os.getcwd()))
print os.path.abspath(os.path.join(os.getcwd(), ".."))

print '***获取上上级目录***'
print os.path.abspath(os.path.join(os.getcwd(), "../.."))

 8、字符串去掉标点符号

>>> string = "Special $#! characters   spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'

特点:

  • 只能识别字母和数字,杀伤力大,会把中文、空格之类的也干掉
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
原文地址:https://www.cnblogs.com/zl1991/p/14373512.html