import shutil
shutil.copy2('source_file', 'destination')
shutil.copytree('source_dir', 'destination')
import re
string = "hello world"
new_string = re.sub(r"world", "python", string)
print(new_string)
if "world" in new_string:
print("Found")
else:
print("Not found")
with open("file.txt", "r") as file:
data = file.read()
with open("file.txt", "a") as file:
file.write("New content")
import csv
with open('file.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
print(', '.join(row))
import xlrd
workbook = xlrd.open_workbook('file.xlsx')
sheet = workbook.sheet_by_index(0)
print(sheet.cell_value(0, 0))
from datetime import datetime, timedelta
now = datetime.now()
today = datetime.today()
tomorrow = today + timedelta(days=1)
import random
random_number = random.randint(1, 100)
import filecmp
if filecmp.cmp('file1.txt', 'file2.txt'):
print("The files are the same")
else:
print("The files are different")
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--input", help="input file name")
args = parser.parse_args()
print(args.input)
import time
while True:
print("Hello")
time.sleep(1) # wait for 1 second
import smtplib
from email.mime.text import MIMEText
msg = 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()
import re
match = re.search(r"world", "hello world")
print(match.group())
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(data)
new_data = json.loads(json_string)
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
print(root.tag)
import PyPDF2
pdf_file = open('file.pdf', 'rb')
reader = PyPDF2.PdfReader(pdf_file)
text = ""
for page in reader.pages:
text += page.text
import requests
response = requests.get('http://example.com')
print(response.content)
import socket
print(socket.gethostbyname(socket.gethostname()))
import qrcode
img = qrcode.make('Hello, World!')
img.save('qrcode.png')
import os
size = os.path.getsize('file.txt')
from PIL import Image
img = Image.open('image.jpg')
img = img.resize((400, 300))
img.save('new_image.jpg')
- 反转字符串
string = "hello world"
new_string = string[::-1]
print(new_string)
string = "hello world"
word_count = len(string.split())
print(word_count)
from fuzzywuzzy import fuzz
ratio = fuzz.ratio("hello world", "helloworld")
print(ratio)
import time
from tqdm import tqdm
for i in tqdm(range(100)):
time.sleep(0.1)
import zipfile
with zipfile.ZipFile('file.zip', 'w') as zip:
zip.write('file.txt')
import ftplib
ftp = 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()
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(b'Hello, World!', ('<broadcast>', 12345))
s.close()
import pyautogui
pyautogui.moveTo(100, 100, duration=1)
pyautogui.click(button='left')
import pyperclip
text = pyperclip.paste()
pyperclip.copy('New text')
import logging
logging.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')
import platform
print(platform.system())
print(platform.release())
import random
class Dice:
def throw(self):
return random.randint(1, 6)
dice = Dice()
result = dice.throw()
print(result)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
a = 5
b = 3
print(add(a, b))
print(subtract(a, b))
print(multiply(a, b))
print(divide(a, b))
try:
x = 1 / 0
except ZeroDivisionError as e:
print(e)
finally:
print("Finally block")
from PIL import Image
img = Image.open('image.jpg')
img.thumbnail((100, 100))
img.save('thumbnail.jpg')
import requests
response = 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']
import os
os.system('ls -l')
import subprocess
subprocess.Popen(['python', 'script.py'])
- 爬虫去重
from collections import defaultdict
url_list = ['http://example.com', 'http://example.com', 'http://google.com']
url_dict = defaultdict(int)
for url in url_list:
url_dict[url] += 1
print(url_dict.keys())
import itchat
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
return "I received: " + msg.text
itchat.auto_login(hotReload=True)
itchat.run()
import random
responses = ["Hello", "Hi", "How are you?", "I'm fine.", "Goodbye"]
while True:
message = input("You: ")
if message == "exit":
break
response = random.choice(responses)
print("Bot: " + response)
numbers = [1, 2, 3, 4, 5]
print(max(numbers))
print(min(numbers))
code = """
for i in range(10):
print(i)
"""
exec(code)
with open("file.bin", "wb") as file:
data = bytes([0x01, 0x02, 0x03])
file.write(data)
import pandas as pd
data = pd.read_csv('file.csv')
data = data.dropna() # remove null values
data = data.sort_values('column') # sort by column
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
authorizer = DummyAuthorizer()
authorizer.add_anonymous('/')
handler = FTPHandler
handler.authorizer = authorizer
server = FTPServer(('localhost', 21), handler)
server.serve_forever()
import sqlite3
connection = 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()
from http.server import HTTPServer, BaseHTTPRequestHandler
class 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()
import hashlib
message = "Hello, World!"
hash_object = hashlib.sha256(message.encode('utf-8'))
hash_value = hash_object.hexdigest()
print(hash_value)
import random
responses = {
"hello": ["Hello", "Hi", "How are you?"],
"goodbye": ["Goodbye", "See you later", "Take care"]
}
while True:
message = input("You: ")
if message == "exit":
break
for keyword in responses.keys():
if keyword in message.lower():
response = random.choice(responses[keyword])
print("Bot: " + response)
break
else:
print("Bot: Sorry, I don't understand.")
以上是50个常用Python脚
原文地址:https://blog.csdn.net/m0_55877125/article/details/130041895
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_18157.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。