100个必会的python脚本,python脚本入门教程

大家好,给大家分享一下100个必会的python脚本,很多人还不知道这一点。下面详细解释一下。现在让我们来看看!

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 <file>")

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))

猜你喜欢

转载自blog.csdn.net/mynote/article/details/132516195