The os module python - Exercises

Exercise 1

  1. In the current directory new directory img, which contains multiple files,
    the file names are different (X4G5.png)
  2. The current list of all img suffix name changed to the end of .jpg .png

program

import random
import string
import os

def gen_code(len=4):
    # 随机生成四位随机数
    li = random.sample(string.ascii_letters+string.digits,len)
    # print(li)
    return  ''.join(li)
#
# gen_code()
def creat_file():
    # 随机生成多个文件名
    li = {gen_code() for i in range(100)}
    os.mkdir('img')
    for name in li:
        os.mknod('img/' + name + '.png')
# creat_file()

def modify_suffix(dirname,old_suffix,new_suffix):
    """
    :param dirname: 要操作的目录
    :param old_suffix: 只前的后缀名
    :param new_suffix: 新的后缀名
    :return:
    """
    # 1.要判断查找的目录是否存在 如果不存在 报错
    if os.path.exists(dirname):
        # 2.找出所有以old_suffix(.png)结尾的文件
        pngfile = [filename for filename in os.listdir(dirname)
                   if filename.endswith(old_suffix)]
        # 3.将后缀名和文件名分离 留下文件名
        basefile = [os.path.splitext(filename)[0]
                    for filename in pngfile]
        # 4.重明名文件
        for filename in basefile:
            oldname = os.path.join(dirname,filename+old_suffix)
            newname = os.path.join(dirname,filename+new_suffix)
            os.rename(oldname,newname)
            print('%s命名为%s成功' %(oldname,newname))
    else:
        print('%s 不存在,不能操作' %(dirname))

modify_suffix('img','.html','.php')

English II

Using the time.time () method, we can calculate the two points in time
the time interval between, but sometimes we want / etc / group
time of the last file m / a / c / time, the corresponding date This information
and save the file in another file date.txt
program

import os
import time
time1 = os.path.getctime('/etc/group')
print(time1)
tuple_time = time.localtime(time1)
print(tuple_time)
year = tuple_time.tm_year
month = tuple_time.tm_mon
day = tuple_time.tm_mday
print(year,month,day)
print(type(year))
print(type(month))
print(type(day))
with open('data.txt','a') as f:
    f.write('%d %d %d' %(year,month,day))
    f.write('\n')

Here Insert Picture Description
result
Here Insert Picture Description

Published 57 original articles · won praise 0 · Views 241

Guess you like

Origin blog.csdn.net/qq_45652989/article/details/103951395