50个常用Python脚本的代码示例:

  1. 复制文件和目录
import shutilshutil.copy2('source_file', 'destination')shutil.copytree('source_dir', 'destination')
  1. 字符串替换和查找
import restring = "hello world"new_string = re.sub(r"world", "python", string)print(new_string)if "world" in new_string:print("Found")else:print("Not found")
  1. 文件读写操作
with open("file.txt", "r") as file:data = file.read()with open("file.txt", "a") as file:file.write("New content")
  1. 解析CSV文件
import csvwith open('file.csv', newline='') as csvfile:reader = csv.reader(csvfile, delimiter=',', quotechar='|')for row in reader:print(', '.join(row))
  1. 解析Excel文件
import xlrdworkbook = xlrd.open_workbook('file.xlsx')sheet = workbook.sheet_by_index(0)print(sheet.cell_value(0, 0))
  1. 计算日期和时间
from datetime import datetime, timedeltanow = datetime.now()today = datetime.today()tomorrow = today + timedelta(days=1)
  1. 生成随机数
import randomrandom_number = random.randint(1, 100)
  1. 判断两个文件是否相同
import filecmpif filecmp.cmp('file1.txt', 'file2.txt'):print("The files are the same")else:print("The files are different")
  1. 从命令行读取参数
import argparseparser = argparse.ArgumentParser()parser.add_argument("--input", help="input file name")args = parser.parse_args()print(args.input)
  1. 定时执行脚本
import timewhile True:print("Hello")time.sleep(1) # wait for 1 second
  1. 发送电子邮件
import smtplibfrom email.mime.text import MIMETextmsg = MIMEText('This is the body of the email')msg['Subject'] = 'Subject'msg['From'] = 'sender@example.com'msg['To'] = 'recipient@example.com's = smtplib.SMTP('localhost')s.sendmail('sender@example.com', ['recipient@example.com'], msg.as_string())s.quit()
  1. 使用正则表达式匹配字符串
import rematch = re.search(r"world", "hello world")print(match.group())
  1. 使用JSON格式处理数据
import jsondata = {"name": "John","age": 30,"city": "New York"}json_string = json.dumps(data)new_data = json.loads(json_string)
  1. 解析XML文件
import xml.etree.ElementTree as ETtree = ET.parse('file.xml')root = tree.getroot()print(root.tag)
  1. 将PDF转换成文本文件
import PyPDF2pdf_file = open('file.pdf', 'rb')reader = PyPDF2.PdfReader(pdf_file)text = ""for page in reader.pages:text += page.text
  1. 爬取网页内容
import requestsresponse = requests.get('http://example.com')print(response.content)
  1. 获取本机IP地址
import socketprint(socket.gethostbyname(socket.gethostname()))
  1. 生成二维码
import qrcodeimg = qrcode.make('Hello, World!')img.save('qrcode.png')
  1. 计算文件大小
import ossize = os.path.getsize('file.txt')
  1. 对图片进行处理
from PIL import Imageimg = Image.open('image.jpg')img = img.resize((400, 300))img.save('new_image.jpg')
  1. 反转字符串
string = "hello world"new_string = string[::-1]print(new_string)
  1. 计算字符串中单词的数量
string = "hello world"word_count = len(string.split())print(word_count)
  1. 模糊匹配字符串
from fuzzywuzzy import fuzzratio = fuzz.ratio("hello world", "helloworld")print(ratio)
  1. 显示进度条
import timefrom tqdm import tqdmfor i in tqdm(range(100)):time.sleep(0.1)
  1. 创建ZIP文件
import zipfilewith zipfile.ZipFile('file.zip', 'w') as zip:zip.write('file.txt')
  1. 使用FTP上传和下载文件
import ftplibftp = ftplib.FTP()ftp.connect('ftp.example.com')ftp.login('username', 'password')ftp.cwd('/uploads')with open('file.txt', 'rb') as file:ftp.storbinary('STOR file.txt', file)ftp.quit()
  1. 通过网络发送广播消息
import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)s.sendto(b'Hello, World!', ('', 12345))s.close()
  1. 控制键盘和鼠标
import pyautoguipyautogui.moveTo(100, 100, duration=1)pyautogui.click(button='left')
  1. 剪贴板操作
import pypercliptext = pyperclip.paste()pyperclip.copy('New text')
  1. 创建和管理日志文件
import logginglogging.basicConfig(filename='app.log', level=logging.INFO)logging.debug('This is a debug message')logging.info('This is an informational message')logging.warning('This is a warning message')logging.error('This is an error message')logging.critical('This is a critical message')
  1. 打印系统信息
import platformprint(platform.system())print(platform.release())
  1. 投掷骰子模拟游戏
import randomclass Dice:def throw(self):return random.randint(1, 6)dice = Dice()result = dice.throw()print(result)
  1. 编写简单的计算器
def add(a, b):return a + bdef subtract(a, b):return a - bdef multiply(a, b):return a * bdef divide(a, b):return a / ba = 5b = 3print(add(a, b))print(subtract(a, b))print(multiply(a, b))print(divide(a, b))
  1. 处理异常和错误
try:x = 1 / 0except ZeroDivisionError as e:print(e)finally:print("Finally block")
  1. 生成缩略图
from PIL import Imageimg = Image.open('image.jpg')img.thumbnail((100, 100))img.save('thumbnail.jpg')
  1. 使用Google Maps API获取地图数据
import requestsresponse = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA')json_data = response.json()lat = json_data['results'][0]['geometry']['location']['lat']lng = json_data['results'][0]['geometry']['location']['lng']
  1. 调用外部命令
import osos.system('ls -l')
  1. 使用subprocess模块启动后台任务
import subprocesssubprocess.Popen(['python', 'script.py'])
  1. 爬虫去重
from collections import defaultdicturl_list = ['http://example.com', 'http://example.com', 'http://google.com']url_dict = defaultdict(int)for url in url_list:url_dict[url] += 1print(url_dict.keys())
  1. 自动化微信账号管理
import itchat@itchat.msg_register(itchat.content.TEXT)def text_reply(msg):return "I received: " + msg.textitchat.auto_login(hotReload=True)itchat.run()
  1. 简单聊天机器人
import randomresponses = ["Hello", "Hi", "How are you?", "I'm fine.", "Goodbye"]while True:message = input("You: ")if message == "exit":breakresponse = random.choice(responses)print("Bot: " + response)
  1. 查找最大值和最小值
numbers = [1, 2, 3, 4, 5]print(max(numbers))print(min(numbers))
  1. 将字符串转换为Python代码并执行
code = """for i in range(10):print(i)"""exec(code)
  1. 生成二进制文件
with open("file.bin", "wb") as file:data = bytes([0x01, 0x02, 0x03])file.write(data)
  1. 数据清洗和处理
import pandas as pddata = pd.read_csv('file.csv')data = data.dropna() # remove null valuesdata = data.sort_values('column') # sort by column
  1. 实现FTP服务器
from pyftpdlib.authorizers import DummyAuthorizerfrom pyftpdlib.handlers import FTPHandlerfrom pyftpdlib.servers import FTPServerauthorizer = DummyAuthorizer()authorizer.add_anonymous('/')handler = FTPHandlerhandler.authorizer = authorizerserver = FTPServer(('localhost', 21), handler)server.serve_forever()
  1. 数据库连接和查询操作
import sqlite3connection = sqlite3.connect('example.db')cursor = connection.cursor()cursor.execute("CREATE TABLE example (id INTEGER PRIMARY KEY, name TEXT)")cursor.execute("INSERT INTO example (name) VALUES ('John')")data = cursor.execute("SELECT * FROM example")for row in data:print(row)connection.close()
  1. 实现简单的Web服务器
from http.server import HTTPServer, BaseHTTPRequestHandlerclass MyHandler(BaseHTTPRequestHandler):def do_GET(self):self.send_response(200)self.send_header('Content-type', 'text/html')self.end_headers()message = "Hello, World!"self.wfile.write(bytes(message, "utf8"))httpd = HTTPServer(('localhost', 8080), MyHandler)httpd.serve_forever()
  1. 使用Python实现加密算法
import hashlibmessage = "Hello, World!"hash_object = hashlib.sha256(message.encode('utf-8'))hash_value = hash_object.hexdigest()print(hash_value)
  1. 实现基本的人工智能
import randomresponses = {"hello": ["Hello", "Hi", "How are you?"],"goodbye": ["Goodbye", "See you later", "Take care"]}while True:message = input("You: ")if message == "exit":breakfor keyword in responses.keys():if keyword in message.lower():response = random.choice(responses[keyword])print("Bot: " + response)breakelse:print("Bot: Sorry, I don't understand.")

以上是50个常用Python脚