注意区分路径,目录,文件
路径:path
目录:dir
文件:file
python中的路径分割符
查看系统的分割符:
import os
os.sep
因此,可以直接用os.sep代替使用斜杆或反斜杆
在Windows系统下的分隔符是:\(反斜杠)
在Linux系统下的分隔符是:/(斜杠)
python中路径的三种写法:
“C:/Users/shentao/Desktop/TCGA-AO-A0J8” 非转义
“C:\\Users\\shentao\\Desktop\\TCGA-AO-A0J8” 转义的方式
r“C:\Users\shentao\Desktop\TCGA-AO-A0J8” 声明字符串不需要转义
注意在windows就只用window的路径表示方法
new_dir = str(os.getcwd()).replace("\\","/")
python中os.path常用模块
os.path.sep:路径分隔符 linux下就用这个了’/’
os.path.curdir:当前目录
os.path.pardir:父目录
os.path.abspath(path):绝对路径
os.path.join(): 常用来链接路径
os.path.split(path): 把path分为目录和文件两个部分,(head, tail)以列表返回
os.path.dirname(path):返回head
os.path.basename(path):返回tail
os.path.splitdrive(path):drive
os.path.splitext(path):extension, (root, ext)
![](https://i-blog.csdnimg.cn/blog_migrate/5cd2a16363e6383f60431881f0ab3b45.png)
![](https://i-blog.csdnimg.cn/blog_migrate/874fdafc192767fe2adceea26de8bdc3.png)
python脚本的当前路径
sys.argv[0]
import sys
print sys.argv[0]#获得的是当前执行脚本的位置(若在命令行执行的该命令,则为空)
sys.path是Python会去寻找模块的搜索路径列表,sys.path[0]和sys.argv[0]是一回事因为Python会自动把sys.argv[0]加入sys.path
os模块
import os
print os.getcwd()#获得当前工作目录
print os.path.abspath('.')#获得当前工作目录
print os.path.abspath('..')#获得当前工作目录的父目录
printos.path.abspath(os.curdir)#获得当前工作目录
注:argv[0]只是得到的是当前脚本的绝对位置;而os模块中的几种获得路径的方法,得到的是当前的工作目录,如:open('1.txt','r'),则会在当前工作目录查找该文件。即大部分的文件操作都是相对于当前工作路径。
os.getcwd()取的是起始执行目录
sys.path[0]或sys.argv[0]取的是被初始执行的脚本的所在目录
os.path.split(os.path.realpath(__file__))[0]取的是__file__所在文件test_path.py的所在目录
改变当前工作路径
可以用:os.chdir(path)
如os.chdir(E:\Program Files),则大部分的文件操作就会是相对于E:\dir1。fobj = open('Hello.txt'),实际会打开E:\Program Files\Hello.txt文件
目录相关模块
os模块在python参考手册16节
os.path模块在Python参考手册11.2节
shutil模块在python参考手册11.10节
os模块--目录操作
os.remove
删除文件
os.rmdir
删除目录
glob模块的glob()
得到的是文件和目录下的完整的路径
os.listdir()
只列出给定目录下的文件和文件夹的名字,但不是完整的路径
![](https://i-blog.csdnimg.cn/blog_migrate/7991b1025968110b573da630a7ef7ac1.png)
os.scandir()
![](https://i-blog.csdnimg.cn/blog_migrate/8dea7d557d0adf0abc1944776e816714.png)
os.walk()
![](https://i-blog.csdnimg.cn/blog_migrate/f01b135012208e87ee038767eeb29f89.png)
def scan_files(directory, prefix=None, postfix=None):
files_list = []
for root, sub_dirs, files in os.walk(directory):
for special_file in files:
if postfix:
if special_file.endswith(postfix):
files_list.append(os.path.join(root, special_file))
elif prefix:
if special_file.startswith(prefix):
files_list.append(os.path.join(root, special_file))
else:
files_list.append(os.path.join(root, special_file))
return files_list
os.path模块--目录操作
![](https://i-blog.csdnimg.cn/blog_migrate/33bc3b1823381c7f55fa4985fa0fe650.png)
os.path.join('datasets', 'image', 'test.jpg')
os.path.split()的功能等价于os.path.dirname() + os.path.basename()的功能
![](https://i-blog.csdnimg.cn/blog_migrate/3b225c757ea92c3495b7947fe5a26c3c.png)
![](https://i-blog.csdnimg.cn/blog_migrate/6544a3c3128021641bd26246785466db.png)
![](https://i-blog.csdnimg.cn/blog_migrate/311bd9a36fd1f3f95f464db5bd0a9a9b.png)
basename表示基址名
用os.path.exists()方法,判断文件和文件夹是一样
![](https://i-blog.csdnimg.cn/blog_migrate/2c864a077fb1f1d20d2261110c2570ab.png)
可以进一步用是文件还是目录来判断
![](https://i-blog.csdnimg.cn/blog_migrate/b72a4518655e128ba517df69086cbc1e.png)
![](https://i-blog.csdnimg.cn/blog_migrate/47a8dfcff4bca4d8762b35b38e30002b.png)
pathlib模块--目录操作
类图:
![](https://i-blog.csdnimg.cn/blog_migrate/3fdd91470db181a5e572d050be23ca69.png)
PurePath.parts
A tuple giving access to the path’s various components:
>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')
>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\\', 'Program Files', 'PSF')
PurePath.parent
The logical parent of the path
PurePath.name
A string representing the final path component, excluding thedrive and root
PurePath.suffix
The file extension of the final component
PurePath.stem
The final path component, without its suffix
PurePath.as_posix()
Return a string representation of the path with forward slashes (/)
PurePath.as_uri()
Represent the path as a file URI. ValueError is raised if the path isn’t absolute.
>>> p = PurePosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = PureWindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'
PurePath.with_name(name)
Return a new path with the namechanged. If the original path doesn’t have a name, ValueError israised
PurePath.with_suffix(suffix)
Return a new path with the suffixchanged. If the original path doesn’t have a suffix, the new suffix is
appended instead
Path.iterdir()
When the path points to a directory, yield path objects of thedirectory contents
Path.mkdir(mode=0o777, parents=False, exist_ok=False)
Create a new directory at this given path
注意parents参数,可以指定为True,连父目录一起创建
If exist_ok is false (the default), FileExistsErroris raised if the target directory already exists
exist_ok表示存在也没有关系
用pathlib模块中的Path().rglob来递归遍历文件:
from pathlib import Path
src = "/home/"
for item in Path(src).rglob('*.py'):
pass
shutil模块--目录操作
![](https://i-blog.csdnimg.cn/blog_migrate/c210c6879b6c83f3c3499f68ea7d60ab.png)
![](https://i-blog.csdnimg.cn/blog_migrate/be4b6013af1ea06203456d140056c5f2.png)
![](https://i-blog.csdnimg.cn/blog_migrate/86149dfc014aa3d31608399b5f6f3605.png)
![](https://i-blog.csdnimg.cn/blog_migrate/e45a9820c08c233b45f14d81e6ebf736.png)
文件目录操作汇总
import os
import shutil
def move_file(src, dst):
shutil.move(src, dst)
def move_dir(src, dst):
shutil.move(src, dst)
def copy_file(src, dst):
shutil.copy(src, dst)
def copy_dir(src, dst):
shutil.copytree(src, dst)
def delete_file(path):
os.remove(path)
def delete_dir(dir):
shutil.rmtree(dir)
def rename_file(src, dst):
os.rename(src, dst)
def rename_dir(src, dst):
os.rename(src, dst)
def mkdir_singlelayer(path):
os.mkdir(path)
def mkdir_multilayer(path):
os.makedirs(path)