Python可以轻而易举的完成一些自动化的工作,比如处理Excel达成自动化办公,再或者创建自动执行任务,文件的处理等等..
下面分享几个用Python编写的几个简单的例子
import os
# 立即重启
os.system('shutdown -R -T 0')
# 20秒后重启
system("shutdown -r -t 20")
import os
os.system('shutdown -s -t 0')
import os
# 文件夹路径:
folder_path = "/home/file/test/"
# 要在开头添加的文本:
Append_str = "prefix_"
for file in os.listdir(folder_path):
with open(os.path.join(folder_path, file), 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write(append_str+"nn"+content)
print('已修改所有的文件')
import os
# 文件夹路径:
folder_path = "/home/file/test/"
# 要在开头添加的文本:
append_str = "hello_"
# 要修改特定文件的后缀名:
postfix = '.py'
for file in os.listdir(folder_path):
if os.path.splitext(file)[1] == postfix:
with open(os.path.join(folder_path, file), 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write(append_str+"nn"+content)
print('已修改所有的%s文件' % postfix)
import os
import shutil
path1 = 'dir1/'
path2 = 'dir2/'
if not os.path.exists(path2):
os.mkdir(path2)
for file in os.listdir(path1):
old_dir = os.path.join(path1, file)
filename, filetype = os.path.splitext(file)
new_dir = os.path.join(path2, str(int(filename)+199)+filetype)
# os.rename(old_dir, new_dir)
# shutil.move(old_dir, new_dir)
# 上面两种方式都会移动删除掉源文件
shutil.copy(old_dir, new_dir)
import re
import pyperclip
# 中国手机号码正则匹配
phone_regex = re.compile(r'((d{3})(s|-|.)?(d{4})(s|-|.)?(d{4}))')
# 邮箱地址正则匹配
email_regex = re.compile(
r'([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(.[a-zA-Z]{2,4}))')
text = pyperclip.paste()
print('匹配到的所有电话号码为:')
for group in phone_regex.findall(text):
print(group[0])
print('匹配到的所有邮箱地址为:')
for group in email_regex.findall(text):
print(group[0])
# 测试文本
# 我叫ex2tron,电话号码是188-8888-6666,邮箱是:ex2tron@outlook.com,另一个邮箱是:ex2tron@foxmail.com
from PIL import ImageGrab
from pyzbar.pyzbar import decode
import pyperclip
# 1. 从剪贴板中获取图片
img = ImageGrab.grabclipboard()
if img:
try:
# 2. 解码
qrcode = str(decode(img)[0].data)
# 3. 复制到剪贴板
# pyperclip.copy(str(qrcode))
print(qrcode)
# 4. 显示图片
# img.show()
except:
print('No QRCode Found.')
else:
print('No Image Here.')
import winreg
def get_user_path():
# 用户文件夹的地址可以在下面这个注册表中查找
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
"SoftwareMicrosoftWindowsCurrentVersionExplorerShell Folders")
print('桌面', winreg.QueryValueEx(key, 'Desktop')[0])
print('文档', winreg.QueryValueEx(key, 'Personal')[0])
print('音乐', winreg.QueryValueEx(key, 'My Music')[0])
print('图片', winreg.QueryValueEx(key, 'My Pictures')[0])
print('视频', winreg.QueryValueEx(key, 'My Video')[0])
print('下载', winreg.QueryValueEx(
key, '{374DE290-123F-4565-9164-39C4925E467B}')[0])
get_user_path()