跳至主要内容

博文

目前显示的是标签为“os”的博文

python 之 OS模块

Python中的OS模块提供了用于创建和删除目录(文件夹),获取其内容,更改和标识当前目录等功能。 http://python101.pythonlibrary.org/chapter16_os.html https://www.tutorialsteacher.com/python/os-module os.mkdir()函数:创建一个新目录 >>> os.mkdir('c:\\123') os.getcwd()函数:获取当前工作目录 >>> os.getcwd() os.chdir()函数:更改当前工作目录 >>> os.chdir("c:\\123") >>> os.chdir("..") os.rmdir()函数:删除空目录,不能删除当前所在目录 >>> os.rmdir("123") os.listdir()函数:返回指定目录下的所有文件和目录的列表,未指定任何目录,则将返回当前所在目录 >>> os.listdir("C:\python38") >>> os.listdir() Python检查文件或目录是否存在  os.path.exists() 使用path.exists可以快速检查文件或目录是否存在 os.path.isfile() 我们可以使用isfile命令来检查给定的输入是文件还是目录。 os.path.isdir() 如果我们想确认给定路径指向目录,我们可以使用os.path.dir()函数  import   os from   os   import  path   def  main ( ) :      # Print the name of the OS      print ( os . name ) #Check for item existence and type print ( "Item exists:"  +  str ( path. exists ( "1.xlsx" ) ) ) print ( "Item is a f...

批量重命名文件

资料 http://www.runoob.com/python/os-file-methods.html https://www.youtube.com/watch?v=ve2pmm5JqmI 软件 RegName https://www.mobzystems.com/tools/regname/ 是一个基于正则表达式的工具,用于执行复杂的文件重命名操作。它显示与可选模式匹配的文件夹中的文件列表。然后,它允许您将这些文件重命名为另一种模式,包括预览 代码 import os #改变当前工作目录 os.chdir(r'c:\path\to\files') # 打印目录 # print(os.getcwd()) # 打印当前目录所有文件名 # print(os.listdir()) # print(dir(os)) for f in os.listdir():     #如果苹果系统创建了.DS_Store文件,请忽略它     if f == '.DS_Store':         continue     #分割路径,返回路径名和文件扩展名的元组     file_name, file_ext = os.path.splitext(f)     # print(file_name)     # split() 通过指定分隔符对字符串进行切片     f_title, f_course, f_number = file_name.split('-')     # print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext))     # 删除空格     f_title = f_title.strip()     f_course = f_course.strip()     f_number = f_numbe...