# OS系統操作 ###### tags: `python語法` ## 1.更改文件檔名 os.rename ```python= os.rename(“list.txt”,”123.txt”) os.rename(原檔名,新檔名) ``` #### 1.1 批量修改檔名 ```python= # 在指定path路徑下,將該層檔案及資料夾名稱前加上字串 for fname in os.listdir(path): new_fname = " "+fname os.rename(os.path.join(path, fname), os.path.join(path, new_fname)) ``` #### 1.2 顯示檔名 ```python= # 顯示指定路徑下的所有檔案及資料夾名稱 for fd in os.listdir(path): full_path=os.path.join(path,fd) if os.path.isdir(full_path): print('資料夾:',full_path) find_dir(full_path) else: print('檔案:',full_path) ``` ## 2.刪除檔案 os.remove ```python= os.remove(“list.txt”) ``` ## 3.建立資料夾 os.mkdir ```python= import os os.mkdir(“資料夾名稱”) #檢查目錄是否存在,若無,則建立資料夾 dir='myDir' if not os.path.exists(dir): os.mkdir(dir) else: print(dir + '已經建立!') ``` #### 3.1建立多層資料夾os.mkdirs() ```python= os.makedirs("./music/subdir") os.makedirs("./music/a/b") os.makedirs("./music/a/b", exist_ok =True) ``` ## 4.獲取當前目錄 os.getcwd() ```python= os.getcwd() ``` ## 5.返回上層目錄 os.chdir(“../”) ```python= os.chdir(“../”) ``` ## 6.獲取目錄列表 os.listdir(“./”) ```python= os.listdir(“./”) ``` ## 7.刪除資料夾 os.rmdir( ) ```python= os.rmdir(“資料夾名稱") ``` ## 8.批量修改檔名 ```python= import os file_name = “txt文件” file_names = os.listdir(file_name) os.chdir(file_name) for name in file_names : os.rename(name,"要添加的文字"+ name) ``` ## 9.列出所有資料夾與檔案 ```python= import os path='f:\\python' def find_dir(dir): fds=os.listdir(dir) for fd in fds: full_path=os.path.join(dir,fd) if os.path.isdir(full_path): print('資料夾:',full_path) find_dir(full_path) else: print('檔案:',full_path) find_dir(path) ``` ## 10.列出指定結尾檔案 ```python= import os path='f:\\python' for root,dirs,files in os.walk(path): #root 路徑; dirs 資料夾名稱; files 檔案名稱 for file in files: if file.endswith('.py'): #py為結尾 print(os.path.join(root,file)) ``` ## 11.使用os.walk列出所有JPG與PNG檔案 ```python= import fnmatch, os path='f:\\python' exts = ['*.jpg','*.jpeg','*.png'] mathches = [] for root, dirs, files in os.walk(path): for ext in exts: for file in fnmatch.filter(files,ext): matches.append(os.path.join(root, file)) for image in matches: print(image) ``` #### os.walk ```python= ## 定義讀檔路徑function def get_filepaths(directory): """ This function will generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). """ file_paths = [] # List which will store all of the full filepaths. # Walk the tree. for root, directories, files in os.walk(directory): #root 路徑; directories 資料夾名稱; files 檔案名稱 for filename in files: if filename.endswith('.wav'): # Join the two strings in order to form the full filepath. filepath = os.path.join(root, filename) file_paths.append(filepath) # Add it to the list. # pdb.set_trace() return file_paths # Self-explanatory. ```