Python 常用的 50 個提效小指令碼
批次重新命名檔案
import osfor filename in os.listdir('.'): os.rename(filename, filename.replace('old', 'new'))
查詢大檔案
import osfor root, dirs, files in os.walk('.'): for name in files: if os.path.getsize(os.path.join(root, name)) > 1024 * 1024: # 大於1MB print(os.path.join(root, name))
建立目錄結構
import osos.makedirs('dir/subdir/subsubdir', exist_ok=True)
刪除空目錄
import osfor 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 shutilshutil.copy('source.txt', 'destination.txt')
移動檔案
import shutilshutil.move('source.txt', 'destination.txt')
讀取檔案內容
with open('file.txt', 'r') as file: content = file.read()
寫入檔案內容
with open('file.txt', 'w') as file: file.write('Hello, World!')
追加檔案內容
with open('file.txt', 'a') as file: file.write('\nAppend this line.')
檢查檔案是否存在
import osif os.path.exists('file.txt'): print("File exists.")else: print("File does not exist.")
讀取 CSV 檔案
import csvwith open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
寫入 CSV 檔案
import csvdata = [['Name', 'Age'], ['Alice', 30], ['Bob', 25]]with open('data.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(data)
讀取 JSON 檔案
import jsonwith open('data.json', 'r') as file: data = json.load(file)
寫入 JSON 檔案
import jsondata = {'name': 'Alice', 'age': 30}with open('data.json', 'w') as file: json.dump(data, file)
過濾列表中的重複項
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)
反轉列表
my_list = [1, 2, 3, 4, 5]reversed_list = list(reversed(my_list))
合併多個列表
list1 = [1, 2, 3]list2 = [4, 5, 6]combined_list = list1 + list2
獲取列表中的最大值
my_list = [1, 2, 3, 4, 5]max_value = max(my_list)
獲取列表中的最小值
my_list = [1, 2, 3, 4, 5]min_value = min(my_list)
獲取網頁內容
import requestsresponse = requests.get('https://www.example.com')print(response.text)
解析 HTML 頁面
from bs4 import BeautifulSoupsoup = BeautifulSoup(response.text, 'html.parser')titles = soup.find_all('h1')for title in titles: print(title.text)
下載圖片
import requestsimg_data = requests.get('http://example.com/image.jpg').contentwith open('image.jpg', 'wb') as handler: handler.write(img_data)
傳送 HTTP POST 請求
import requestspayload = {'key1': 'value1', 'key2': 'value2'}response = requests.post('https://httpbin.org/post', data=payload)print(response.text)
處理 JSON 響應
import requestsresponse = requests.get('https://api.example.com/data')data = response.json()print(data)
設定超時時間
import requeststry: response = requests.get('https://www.example.com', timeout=5)except requests.Timeout: print("The request timed out")
處理異常
import requeststry: response = requests.get('https://www.example.com') response.raise_for_status()except requests.HTTPError as http_err: print(f"HTTP error occurred: {http_err}")except Exception as err: print(f"Other error occurred: {err}")
使用會話保持連線
import requestssession = requests.Session()response = session.get('https://www.example.com')print(response.text)
獲取響應頭資訊
import requestsresponse = requests.get('https://www.example.com')print(response.headers)
設定自定義請求頭
import requestsheaders = {'User-Agent': 'MyApp/1.0'}response = requests.get('https://www.example.com', headers=headers)print(response.text)
定時執行任務
import scheduleimport timedef job(): print("I'm working...")schedule.every(10).seconds.do(job)while True: schedule.run_pending() time.sleep(1)
傳送電子郵件
import smtplibfrom email.mime.text import MIMETextmsg = 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()
執行系統命令
import subprocessresult = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)print(result.stdout.decode('utf-8'))
壓縮檔案
import zipfilewith zipfile.ZipFile('archive.zip', 'w', zipfile.ZIP_DEFLATED) as zipf: zipf.write('file.txt')
解壓檔案
import zipfilewith zipfile.ZipFile('archive.zip', 'r') as zipf: zipf.extractall('extracted_files')
監控檔案變化
import timeimport osimport hashlibdef get_file_hash(filename): hasher = hashlib.md5() with open(filename, 'rb') as f: buf = f.read() hasher.update(buf) return hasher.hexdigest()last_hash = Nonewhile True: current_hash = get_file_hash('file.txt') if current_hash != last_hash: print("File has changed!") last_hash = current_hash time.sleep(1)
生成隨機數
import randomrandom_number = random.randint(1, 100)print(random_number)
生成隨機字串
import randomimport stringrandom_string = ''.join(random.choices(string.ascii_letters + string.digits, k=12))print(random_string)
生成隨機密碼
import randomimport stringpassword = ''.join(random.choices(string.ascii_letters + string.digits, k=12))print(password)
讀取環境變數
import osapi_key = os.getenv('API_KEY')print(api_key)
統計單詞數
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)
分割字串
text = "apple,banana,orange"fruits = text.split(',')print(fruits)
連線字串
fruits = ['apple', 'banana', 'orange']text = ', '.join(fruits)print(text)
檢查字串是否包含子串
text = "Hello, World!"if "World" in text: print("Found 'World' in the text.")
將字串轉換為大寫
text = "hello, world!"upper_text = text.upper()print(upper_text)
將字串轉換為小寫
text = "HELLO, WORLD!"lower_text = text.lower()print(lower_text)
去除字串首尾空格
text = " Hello, World! "stripped_text = text.strip()print(stripped_text)
去除字串中所有空格
text = "Hello, World!"no_space_text = text.replace(" ", "")print(no_space_text)
格式化字串
name = "Alice"age = 30formatted_text = f"Name: {name}, Age: {age}"print(formatted_text)
高階搬磚 · 目錄
上一篇Pytest的精髓下一篇python socket 模擬 http請求
微信掃一掃
關注該公眾號