os 모듈 파이썬 - 연습

연습 1

  1. 여러 파일이 들어있는 현재 디렉토리에 새 디렉토리 IMG에서,
    파일 이름 (X4G5.png) 다른
  2. .JPG의 .PNG의 끝으로 변경 모든 IMG 접미사 이름의 현재 목록

프로그램

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

영어 II

로 time.time () 메소드를 사용하여, 우리는 시간에 두 점을 계산할 수
사이의 시간 간격, 그러나 때때로 우리는 등 / 원하는 / 그룹
의 마지막 파일 m / A / C / 시간의 시간, 해당 날짜 이 정보는
다른 파일으로 date.txt 및 파일 저장
프로그램

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

그림 삽입 설명 여기
결과
그림 삽입 설명 여기

게시 57 개 원래 기사 · 원의 칭찬 0 · 조회수 241

추천

출처blog.csdn.net/qq_45652989/article/details/103951395