1.os.listdir()函数
os.listdir()函数的具体作用是返回指定目录下所有文件名和目录名(文件夹)
返回值是一个list
例子
新建一个文件夹list,然后在list文件及下新建一个文件夹list1和新建三个文档命名为1.txt,2.txt,3.txt。也可以在list1文件夹下新建一个4.txt。
import os list = 'list' ls = os.listdir(list) print(ls)
输出:
2.os.getcwd()函数
os.getcwd
函数得到当前工作目录,即当前python脚本工作的目录路径。
import os cwd = os.getcwd() print(cwd)输出:
/home/pc314/Documents/jworkplace/python3代码测试
2.path()函数
参考
https://blog.csdn.net/lygzscnt12/article/details/52470017
(1)os.path.split(path)
函数返回一个路径的目录名和文件名
分离文件名与拓展名os.path.splitext(),我是用在将文件进行重新命名。
例子
(2)os.path.exists(path)
用来检验路径是否真的存在,一般我用这个判断是否存在这个文件,然后再用os.mkdir()创建这个不存在的文件夹。
扫描二维码关注公众号,回复:
1523462 查看本文章
例子
import os cwd = os.getcwd() dir,file = os.path.split(cwd) print(dir,file)
输出:
/home/pc314/Documents/jworkplace test
例子(新建如例子1一样的文件)
import os path = 'list' ls = os.listdir(path) file_name,file_type = os.path.splitext(ls[1]) print(file_name) print(file_type)
输出:
1 .txt(3)os.path.join()
连接目录与文件名或目录
例子
path = '/home/pc314/Documents/jworkplace/' file = '1.txt' print(os.path.join(path,file))
结果:
/home/pc314/Documents/jworkplace/1.txt这里面的path也可以是
path = '/home/pc314/Documents/jworkplace'
(4) os.path.isfile()
3.os.system()函数
os.system函数可以使用shell命令
4.os.chdir()函数
os.chdir() 方法用于改变当前工作目录到指定的路径
import os, sys path = "/tmp" # 查看当前工作目录 retval = os.getcwd() print('当前工作目录为 %s' % retval) # 修改当前工作目录 os.chdir( path ) # 查看修改后的工作目录 retval = os.getcwd() print('目录修改成功 %s' % retval)
输出:
当前工作目录为 /home/pc314/Documents/jworkplace/test 目录修改成功 /tmp