Python中常用腳本集錦分享
文件和目錄管理
復(fù)制文件
import shutil
# 復(fù)制源文件到目標(biāo)文件
shutil.copy('source.txt', 'destination.txt')
移動(dòng)文件
import shutil
# 移動(dòng)文件到新的路徑
shutil.move('source.txt', 'destination.txt')
創(chuàng)建目錄結(jié)構(gòu)
import os
# 創(chuàng)建多層目錄,如果已經(jīng)存在則不報(bào)錯(cuò)
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()
寫(xiě)入文件內(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)
寫(xiě)入 CSV 文件
import csv
# 寫(xiě)入數(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)
寫(xiě)入 JSON 文件
import json
# 將數(shù)據(jù)寫(xiě)入 JSON 文件
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as file:
json.dump(data, file)
過(guò)濾列表中的重復(fù)項(xiàng)
# 從列表中去除重復(fù)項(xiàng) my_list = [1, 2, 2, 3, 4, 4, 5] unique_list = list(set(my_list))
排序列表
# 對(duì)列表進(jìn)行排序 my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_list = sorted(my_list)
網(wǎng)絡(luò)請(qǐng)求與爬蟲(chóng)
獲取網(wǎng)頁(yè)內(nèi)容
import requests
# 發(fā)送 GET 請(qǐng)求并獲取網(wǎng)頁(yè)內(nèi)容
response = requests.get('https://www.example.com')
print(response.text)
發(fā)送 HTTP POST 請(qǐng)求
import requests
# 發(fā)送 POST 請(qǐng)求并打印響應(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)
自動(dòng)化任務(wù)
定時(shí)執(zhí)行任務(wù)
import schedule
import time
# 定義定時(shí)執(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)計(jì)單詞數(shù)
# 統(tǒng)計(jì)字符串中的單詞數(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)
連接字符串
# 將列表中的字符串連接為一個(gè)字符串 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)
其他常見(jiàn)功能
生成隨機(jī)數(shù)
import random # 生成1到100之間的隨機(jī)整數(shù) random_number = random.randint(1, 100) print(random_number)
生成隨機(jī)密碼
import random import string # 生成隨機(jī)密碼 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)
運(yùn)行系統(tǒng)命令
import subprocess
# 運(yùn)行系統(tǒng)命令并打印輸出
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))以上就是Python中常用腳本集錦分享的詳細(xì)內(nèi)容,更多關(guān)于Python常用腳本的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python使用re模塊正則提取字符串中括號(hào)內(nèi)的內(nèi)容示例
這篇文章主要介紹了Python使用re模塊正則提取字符串中括號(hào)內(nèi)的內(nèi)容,結(jié)合實(shí)例形式分析了Python使用re模塊進(jìn)行針對(duì)括號(hào)內(nèi)容的正則匹配操作,并簡(jiǎn)單解釋了相關(guān)修正符與正則語(yǔ)句的用法,需要的朋友可以參考下2018-06-06
使用Tensorflow實(shí)現(xiàn)可視化中間層和卷積層
今天小編就為大家分享一篇使用Tensorflow實(shí)現(xiàn)可視化中間層和卷積層,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01
教你用Python寫(xiě)一個(gè)植物大戰(zhàn)僵尸小游戲
這篇文章主要介紹了教你用Python寫(xiě)一個(gè)植物大戰(zhàn)僵尸小游戲,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
python開(kāi)發(fā)實(shí)例之python使用Websocket庫(kù)開(kāi)發(fā)簡(jiǎn)單聊天工具實(shí)例詳解(python+Websocket+J
這篇文章主要介紹了python開(kāi)發(fā)實(shí)例之python使用Websocket庫(kù)開(kāi)發(fā)簡(jiǎn)單聊天工具實(shí)例詳解(python+Websocket+JS),需要的朋友可以參考下2020-03-03
python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的方法
這篇文章主要介紹了python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的方法,涉及Python中os模塊及codecs模塊的相關(guān)使用技巧,需要的朋友可以參考下2015-05-05
python 網(wǎng)絡(luò)編程要點(diǎn)總結(jié)
Python 提供了兩個(gè)級(jí)別訪問(wèn)的網(wǎng)絡(luò)服務(wù):低級(jí)別的網(wǎng)絡(luò)服務(wù)支持基本的 Socket,它提供了標(biāo)準(zhǔn)的 BSD Sockets API,可以訪問(wèn)底層操作系統(tǒng) Socket 接口的全部方法。高級(jí)別的網(wǎng)絡(luò)服務(wù)模塊SocketServer, 它提供了服務(wù)器中心類(lèi),可以簡(jiǎn)化網(wǎng)絡(luò)服務(wù)器的開(kāi)發(fā)。下面看下該如何使用2021-06-06

