注意区分路径,目录,文件
路径: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://img-blog.csdnimg.cn/img_convert/e164373f86562a27f3514a2193976c94.png)
![](https://img-blog.csdnimg.cn/img_convert/33aea1be2a60481c9b0c095c50944fef.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://img-blog.csdnimg.cn/img_convert/94e2dbf34fb76f8ccb0bde5350022b57.png)
os.scandir()
![](https://img-blog.csdnimg.cn/img_convert/b9e092fd0953ec01b62709db00adda8e.png)
os.walk()
![](https://img-blog.csdnimg.cn/img_convert/d8eeb0475a5c8a191bb118d9978bfeea.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://img-blog.csdnimg.cn/img_convert/159dd742e37f27cd68cd896dd1b42721.png)
os.path.join('datasets', 'image', 'test.jpg')
os.path.split()的功能等价于os.path.dirname() + os.path.basename()的功能
![](https://img-blog.csdnimg.cn/img_convert/cc2789c7f82b734cd39fc752476a1ab3.png)
![](https://img-blog.csdnimg.cn/img_convert/ddfbb5ab83489bcf5448edb35c22f4a3.png)
![](https://img-blog.csdnimg.cn/img_convert/4dda3342098ebdb2736fcd8fea229c43.png)
basename表示基址名
用os.path.exists()方法,判断文件和文件夹是一样
![](https://img-blog.csdnimg.cn/img_convert/18828acc2a64f2e2a207561884cef20d.png)
可以进一步用是文件还是目录来判断
![](https://img-blog.csdnimg.cn/img_convert/eedff78b314cb5b2d6063cf885b29803.png)
![](https://img-blog.csdnimg.cn/img_convert/d05da71ee528c6ff483c7543df9c196f.png)
pathlib模块--目录操作
类图:
![](https://img-blog.csdnimg.cn/img_convert/f8e8f2e1146f5a54523853b0ad057881.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://img-blog.csdnimg.cn/img_convert/eff4b759e2c63e8eccf4483228fd49a8.png)
![](https://img-blog.csdnimg.cn/img_convert/f055b10c7e4f31ee1181eb95f191826d.png)
![](https://img-blog.csdnimg.cn/img_convert/ea870a0b029abfc73c750bb6c986c5cc.png)
![](https://img-blog.csdnimg.cn/img_convert/3f197e07dd8d01b1fd7e36442a956877.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)