Python學習 遍歷檔案作批量處理

2021-10-01 02:34:59 字數 847 閱讀 7434

__author__ = 'sym'

__date__ = '19-11-26'

import os

def repair(rootdir):

for root,dirs,files in os.walk(rootdir):

for file in files:

p_rootdir = os.path.join(root, file)

print(p_rootdir)

os.system("iconv %s -f us-ascii -t utf-8 -o %s" % (p_rootdir,p_rootdir)) # 這裡使用了shell命令

for dir in dirs:

repair(dir)

if __name__ == '__main__':

rootdir = '/home/sym/pycharmprojects/machinelearninginaction/ch04/email/spam' # 指定要修改許可權的目錄

repair(rootdir)

其中for root,dirs,files in os.walk(rootdir):這一句作用是遍歷檔案,各變數含義如下:

rootdir

代表需要遍歷的根資料夾

root

表示正在遍歷的資料夾的名字(根/子)

dirs

記錄正在遍歷的資料夾下的子資料夾集合

files

記錄正在遍歷的資料夾中的檔案集合

找到檔案後批量使用shell命令即可。

python批量匯入檔案 python 批量匯入

usr bin envpythoncoding utf 8importmysqldbdefdb execute sql dbs mysqldb.connect host localhost user root passwd root db db port 3306 cursor dbs.cursor...

Python學習 批量更改檔名

如下 import os import time defbatch rename path global file num ifnot os.path.isdir path andnot os.path.isfile path return false if os.path.isfile path ...

python 檔案遍歷

1.使用os.listdir dir 得到一定list包含了目錄下所有的檔案和資料夾 os.path.join dir,filename 獲得檔案的全路徑 os.path.isdir filepath 判斷是不是乙個dir import os,sys import re def deal log l...