Python中常用腳本集錦分享
更新時間:2024年11月05日 09:16:49 作者:PythonFun
這篇文章為大家收集了一些常用Python腳本,作為平時練手使用,也可以作為自己的筆記,希望對大家有一定的幫助
文件和目錄管理
復(fù)制文件
import shutil
# 復(fù)制源文件到目標文件
shutil.copy('source.txt', 'destination.txt')
移動文件
import shutil
# 移動文件到新的路徑
shutil.move('source.txt', 'destination.txt')
創(chuàng)建目錄結(jié)構(gòu)
import os
# 創(chuàng)建多層目錄,如果已經(jīng)存在則不報錯
os.makedirs('dir/subdir/subsubdir', exist_ok=True)
刪除空目錄
import os
# 刪除當(dāng)前目錄下的所有空目錄
for root, dirs, files in os.walk('.', topdown=False):
for name in dirs:
dir_path = os.path.join(root, name)
if not os.listdir(dir_path):
os.rmdir(dir_path)
查找大文件
import os
# 查找當(dāng)前目錄及子目錄下大于1MB的文件
for root, dirs, files in os.walk('.'):
for name in files:
if os.path.getsize(os.path.join(root, name)) > 1024 * 1024:
print(os.path.join(root, name))
檢查文件是否存在
import os
# 檢查指定文件是否存在
if os.path.exists('file.txt'):
print("File exists.")
else:
print("File does not exist.")
讀取文件內(nèi)容
with open('file.txt', 'r') as file:
content = file.read()
寫入文件內(nèi)容
with open('file.txt', 'w') as file:
file.write('Hello, World!')
數(shù)據(jù)處理
讀取 CSV 文件
import csv
# 讀取 CSV 文件并打印每一行
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
寫入 CSV 文件
import csv
# 寫入數(shù)據(jù)到 CSV 文件
data = [['Name', 'Age'], ['Alice', 30], ['Bob', 25]]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
讀取 JSON 文件
import json
# 讀取 JSON 文件
with open('data.json', 'r') as file:
data = json.load(file)
寫入 JSON 文件
import json
# 將數(shù)據(jù)寫入 JSON 文件
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as file:
json.dump(data, file)
過濾列表中的重復(fù)項
# 從列表中去除重復(fù)項 my_list = [1, 2, 2, 3, 4, 4, 5] unique_list = list(set(my_list))
排序列表
# 對列表進行排序 my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_list = sorted(my_list)
網(wǎng)絡(luò)請求與爬蟲
獲取網(wǎng)頁內(nèi)容
import requests
# 發(fā)送 GET 請求并獲取網(wǎng)頁內(nèi)容
response = requests.get('https://www.example.com')
print(response.text)
發(fā)送 HTTP POST 請求
import requests
# 發(fā)送 POST 請求并打印響應(yīng)
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=payload)
print(response.text)
處理 JSON 響應(yīng)
import requests
# 獲取并解析 JSON 響應(yīng)
response = requests.get('https://api.example.com/data')
data = response.json()
print(data)
下載圖片
import requests
# 下載并保存圖片
img_data = requests.get('http://example.com/image.jpg').content
with open('image.jpg', 'wb') as handler:
handler.write(img_data)
自動化任務(wù)
定時執(zhí)行任務(wù)
import schedule
import time
# 定義定時執(zhí)行的任務(wù)
def job():
print("I'm working...")
# 每10秒執(zhí)行一次任務(wù)
schedule.every(10).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)
發(fā)送電子郵件
import smtplib
from email.mime.text import MIMEText
# 發(fā)送電子郵件
msg = MIMEText('Hello, this is a test email.')
msg['Subject'] = 'Test Email'
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient@example.com'
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
統(tǒng)計單詞數(shù)
# 統(tǒng)計字符串中的單詞數(shù)
text = "This is a test. This is only a test."
word_count = len(text.split())
print(f"Word count: {word_count}")
替換字符串
# 替換字符串中的子串
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)
連接字符串
# 將列表中的字符串連接為一個字符串 fruits = ['apple', 'banana', 'orange'] text = ', '.join(fruits) print(text)
格式化字符串
# 使用 f-string 格式化字符串
name = "Alice"
age = 30
formatted_text = f"Name: {name}, Age: {age}"
print(formatted_text)
其他常見功能
生成隨機數(shù)
import random # 生成1到100之間的隨機整數(shù) random_number = random.randint(1, 100) print(random_number)
生成隨機密碼
import random import string # 生成隨機密碼 password = ''.join(random.choices(string.ascii_letters + string.digits, k=12)) print(password)
讀取環(huán)境變量
import os
# 讀取指定環(huán)境變量
api_key = os.getenv('API_KEY')
print(api_key)
運行系統(tǒng)命令
import subprocess
# 運行系統(tǒng)命令并打印輸出
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))以上就是Python中常用腳本集錦分享的詳細內(nèi)容,更多關(guān)于Python常用腳本的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python使用re模塊正則提取字符串中括號內(nèi)的內(nèi)容示例
這篇文章主要介紹了Python使用re模塊正則提取字符串中括號內(nèi)的內(nèi)容,結(jié)合實例形式分析了Python使用re模塊進行針對括號內(nèi)容的正則匹配操作,并簡單解釋了相關(guān)修正符與正則語句的用法,需要的朋友可以參考下2018-06-06
使用Tensorflow實現(xiàn)可視化中間層和卷積層
今天小編就為大家分享一篇使用Tensorflow實現(xiàn)可視化中間層和卷積層,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python開發(fā)實例之python使用Websocket庫開發(fā)簡單聊天工具實例詳解(python+Websocket+J
這篇文章主要介紹了python開發(fā)實例之python使用Websocket庫開發(fā)簡單聊天工具實例詳解(python+Websocket+JS),需要的朋友可以參考下2020-03-03
python實現(xiàn)統(tǒng)計代碼行數(shù)的方法
這篇文章主要介紹了python實現(xiàn)統(tǒng)計代碼行數(shù)的方法,涉及Python中os模塊及codecs模塊的相關(guān)使用技巧,需要的朋友可以參考下2015-05-05
python 網(wǎng)絡(luò)編程要點總結(jié)
Python 提供了兩個級別訪問的網(wǎng)絡(luò)服務(wù):低級別的網(wǎng)絡(luò)服務(wù)支持基本的 Socket,它提供了標準的 BSD Sockets API,可以訪問底層操作系統(tǒng) Socket 接口的全部方法。高級別的網(wǎng)絡(luò)服務(wù)模塊SocketServer, 它提供了服務(wù)器中心類,可以簡化網(wǎng)絡(luò)服務(wù)器的開發(fā)。下面看下該如何使用2021-06-06

