目錄
- 1. OS模塊
- 2. shutil模塊
- 3. globa模塊
- glob的幾種用法
本文摘自微信公眾號 GitPython:十個 Python 自動化常用操作。如有侵權(quán),聯(lián)系必刪。
1. OS模塊
導入:import os
1. 遍歷文件夾
批量操作的前提就是對文件夾進行遍歷,os.walk
遍歷文件夾后產(chǎn)生三個參數(shù):
- 當前文件夾路徑
- 包含文件夾的名稱(列表形式)
- 包含文件名稱(列表形式)
代碼如下(按需求更改目標路徑即可):
for dirpath, dirnames, filenames in os.walk(r'C:\\Program Files (x86)'):
print(f'打開文件夾{dirpath}') # 當前文件夾路徑
if dirnames:
print(dirnames) # 包含文件夾名稱(列表形式)
if filenames:
print(filenames) # 包含文件名稱(列表形式)
print('-' * 10)
# 輸出結(jié)果:
打開文件夾C:\\Program Files (x86)
['360', 'BirdWallpaper', 'Common Files', 'erl5.9.3.1', 'InstallShield Installation Information', 'Intel', 'Internet Explorer', 'IQIYI Video', 'Java', 'Kingsoft', 'Microsoft Office', 'Microsoft.NET', 'MSBuild', 'NetSarang', 'NVIDIA Corporation', 'Reference Assemblies', 'Sangfor', 'Sinfor', 'SogouInput', 'svnfile', 'Tencent', 'UltraEdit', 'VMware', 'Windows Defender', 'Windows Mail', 'Windows Media Player', 'Windows Multimedia Platform', 'Windows NT', 'Windows Photo Viewer', 'Windows Portable Devices', 'Windows Sidebar', 'WindowsPowerShell', 'Youdao']
['desktop.ini', '微軟常用運行庫合集_2019.07.20_X64.exe']
----------
打開文件夾C:\\Program Files (x86)\360
['360bizhi', '360Safe', '360SD']
2. 目標路徑是否是文件
給定一個目標路徑path
,通過一行代碼判斷該路徑是文件夾還是文件夾路徑,使用os.path.isfile(path)
,返回True
或False
。
path = r'C:\Users\Administrator\Desktop\doc\note.md'
print(os.path.isfile(path)) # True
path = 'xxx'
print(os.path.isfile(path)) # False
3. 獲取路徑中的文件名
os模塊方式:os.path.basename
可以直接從絕對路徑中獲取最后的文件名
path = r'C:\Users\Administrator\Desktop\doc\note.md'
print(os.path.basename(path))
print(path.split('\\')[-1])
# note.md
切割字符串方式:path.split('\\')[-1]
path = r'C:\Users\Administrator\Desktop\doc\note.md'
print(path.split('\\')[-1])
# note.md
4. 創(chuàng)建文件夾
創(chuàng)建文件夾的代碼非常常用,因為往往生成的新文件都希望有個新的文件夾存儲。
dirpath = 'xxx'
os.mkdir(dirpath)
# 這樣會在該`py`文件同一目錄下生成名為`xxx`的文件夾
但如果存在同名文件夾會報錯FileExistsError: [WinError 183] 當文件已存在時,無法創(chuàng)建該文件。: 'xxx'
,為了避免報錯可在創(chuàng)建前先判斷是否存在:
dirpath = 'xxx'
if not os.path.exists(dirpath):
os.mkdir(dirpath)
5. 獲取桌面路徑
- 獲取桌面路徑非常常用,可使用
os.path.join(os.path.expanduser("~"), 'Desktop')
獲取桌面的絕對路徑
- 好處:把數(shù)據(jù)放到桌面上,在不同的電腦上都能調(diào)用代碼對數(shù)據(jù)進行處理。
- 如果是在一臺電腦上把桌面路徑固定在字符串中,則換一臺電腦就必須修改桌面路徑
desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop')
print(desktop_path)
# C:\Users\Administrator\Desktop
封裝成一個函數(shù)進行調(diào)用
def get_desktop_path():
return os.path.join(os.path.expanduser("~"), 'Desktop')
6. 重命名文件/文件夾 使用os.rename()
方法
os.rename('xxx', 'xxx2') # 重命名文件夾
os.rename('test.txt', 'test2.txt') # 重命名文件
7. 批處理文件 - 1
除了os.walk
外,在非遍歷各級文件夾時,還可用os.scandir()
獲取指定路徑的全部或符合條件的文件,使用for
循環(huán),獲取循環(huán)變量的name
和path
:
path = '.'
for file in os.scandir(path):
print(file.name, file.path)
# 輸出結(jié)果:
aaa .\aaa
os模塊.py .\os模塊.py
test2.txt .\test2.txt
xxx2 .\xxx2
# 如果path是絕對路徑,下邊打印出來的也是絕對路徑
8. 批處理文件 - 2
獲取指定路徑的全部或符合條件的文件第二種方法使用os.listdir()
獲取文件名:
path = r'F:\python\python-basic\tips\自動化常用操作'
for file in os.listdir(path):
print(file)
# 輸出結(jié)果:
aaa
os模塊.py
test2.txt
xxx2
2. shutil模塊
9. 移動文件/文件夾(并重命名) shutil
常用于 移動文件/文件夾,使用shutil.move()
方法:
import shutil
# 把當前目錄下的shutil_test.txt文件移動到當前目錄的bbb文件夾下
shutil.move(r'.\shutil_test.txt', r'.\bbb/')
# 把當前目錄下的shutil_test2.txt文件移動到當前目錄bbb文件夾下,并重命名為shutil_test22.txt
shutil.move(r'.\shutil_test2.txt', r'.\bbb/shutil_test22.txt')
3. globa模塊
10. 批處理文件 - 3
golb
模塊最重要的功能是搜索獲取同一級或各子級下符合條件的文件(絕對路徑),非常適合寫批處理的代碼。
- 對大量文件進行相同操作,在寫完針對一份文件的操作后,只需加上幾行代碼就可以完成批處理全部文件的工作
- 參數(shù):
*
表示任意字符長度;**/*
表示用通配符指代給定路徑下的任何一層;recursive
為True
表示允許遍歷搜索,默認為False
import glob
for file in glob.glob('**/*', recursive=True):
print(file)
# 輸出結(jié)果:
aaa
bbb
glob模塊.py
os模塊.py
shutil模塊.py
test2.txt
xxx2
bbb\shutil_test.txt
bbb\shutil_test22.txt
glob
可獲取指定路徑下文件的絕對路徑,也可接受 通配符 搜索,拓寬了靈活程度。
glob的幾種用法
glob
最重要的功能是 搜索獲取同一級或各子級下符合條件的文件(絕對路徑)。
- 導入:
import glob
- demo1:獲取當前目錄下所有文件和文件夾及其文件
for file in glob.glob('**/*', recursive=True):
print(file)
# 輸出結(jié)果:
aaa
bbb
glob模塊.py
os模塊.py
shutil模塊.py
test2.txt
xxx2
bbb\shutil_test.txt
bbb\shutil_test22.txt
bbb\w
bbb\w\aaaa.txt
bbb\w\s
bbb\w\s\i.txt
demo2:獲取當前目錄bbb下的文件及其一層子文件
for file in glob.glob('./bbb/*'):
print(file)
# 輸出結(jié)果:
./bbb\shutil_test.txt
./bbb\shutil_test22.txt
./bbb\w
demo3:獲取當前目錄bbb下所有文件和文件夾及其文件
for file in glob.glob('./bbb/**', recursive=True):
print(file)
# 輸出結(jié)果:
./bbb\
./bbb\shutil_test.txt
./bbb\shutil_test22.txt
./bbb\w
./bbb\w\aaaa.txt
./bbb\w\s
./bbb\w\s\i.txt
demo4:獲取當前目錄bbb下嵌套兩層內(nèi)的文件和文件夾
for file in glob.glob('./bbb' + '/*/*'):
print(file)
# 輸出結(jié)果:
./bbb\w\aaaa.txt
./bbb\w\s
demo5:遍歷包含指定名稱的文件和文件夾
import os
arm_path = glob.glob(os.path.join('./bbb', '*.txt'))
print(arm_path)
# 輸出結(jié)果:
['./bbb\\shutil_test.txt', './bbb\\shutil_test22.txt']
到此這篇關于Python 自動化常用操作的文章就介紹到這了,更多相關Python 自動化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python通配符之glob模塊的使用詳解
- Python全局變量與global關鍵字常見錯誤解決方案
- Python中 Global和Nonlocal的用法詳解
- python global關鍵字的用法詳解
- python中的global關鍵字的使用方法