一些简单实用的python脚本案例合集

一些简单实用的python脚本案例合集,第1张

1. 时分转换
def convert(seconds):
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60

    return "%d:%02d:%02d" % (hour, minutes, seconds)

# Driver program
n = 12345
print(convert(n))

2. if- else statement
# Assign a value
number = 50

# Check the is more than 50 or not
if (number >= 50):
    print("You have passed")
else:
    print("You have not passed")
3. 转换图片格式JPEG
import os
import sys
from PIL import Image

if len(sys.argv) > 1:
    if os.path.exists(sys.argv[1]):
        im = Image.open(sys.argv[1])
        target_name = sys.argv[1] + ".jpg"
        rgb_im = im.convert('RGB')
        rgb_im.save(target_name)
        print("Saved as " + target_name)
    else:
        print(sys.argv[1] + " not found")
else:
    print("Usage: convert2jpg.py ")
4. 在系统里寻找文件
import fnmatch
import os

rootPath = '/'
pattern = '*.mp3'

for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        print( os.path.join(root, filename))
5. 随机密码生成器
import string
from random import *
characters = string.ascii_letters + string.punctuation  + string.digits
password =  "".join(choice(characters) for x in range(randint(8, 16)))
print (password)
6. 数一数列表中的字母有几个
# Define the string
string = 'Python Bash Java PHP PHP PERL'
# Define the search string
search = 'P'
# Store the count value
count = string.count(search)
# Print the formatted output
print("%s appears %d times" % (search, count))

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/869742.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存