Python基础知识学习(六)

import os
# 相对路径用的比较多,因为1.简单,2.

# getcwd获取当前文件的绝对路径
result = os.getcwd()
print(result)

# absolute 绝对的
# 在计算机当中,获取当前文件路径用 “.”  ,  获取父文件夹路径 用“..”
result = os.path.abspath('.')
print(result)
result = os.path.abspath('..')
print(result)

# 获取指定文件对应的绝对路径
result = os.path.abspath('周二.txt')
print(result)

# 获取文件路径的某一部分
result = os.path.basename('C:/Users/Administrator/Desktop/第六天')
print('路径的basename{}'.format(result))


result = os.path.commonpath([
    'D:/WeChat/WeChat.exe',
    'D:/YY/yy/YY.exe',
])
print('路径的公共部分为:{}'.format(result))

# 注意:以'/'分割 将路径分成几部分,找到公共的一部分
result = os.path.commonpath([
    'https://daohang.qq.com/?fr=hmpage',
    'https://www.baidu.com/index.php?tn=02049043_6_pg',
])
print('网址的公共部分为:{}'.format(result))

# directory name 获取指定文件所在文件夹路径
result = os.path.dirname('C:/Users/Adminstrator/Desktop/os测试/python.txt')
print(result)
# 注意:此时输出的是字符串  因为输入的路径是字符串


# 获取文件夹信息========================================================
# 文件夹信息包括 创建日期,修改日期,访问日期
import  time
# c:文档是change   实际是create
result = os.path.getctime('C:/Users/Administrator/Desktop/os测试')
print('文件创建日期为:{}'.format(time.localtime(result)))

# a:access 访问
result = os.path.getatime('C:/Users/Administrator/Desktop/os测试')
print('文件的访问日期是:{}'.format(time.localtime(result)))

# m:modify 修改
result = os.path.getmtime('C:/Users/Administrator/Desktop/os测试')
print('文件的修改日期是:{}'.format(time.localtime(result)))

# size 尺寸,大小   获得的的结果是字节(B)
# TB GB MB KB B b       1B = 8b
result = os.path.getsize('C:/Users/Administrator/Desktop/os测试')
print('文件大大小为:{}'.format(result / 1024))

# isFile 判断是否为文件
# os.path.exists()
result = os.path.isfile('C:/Users/Administrator/Desktop/os测试/python.txt')
print('{}'.format(result))

# 文件分割---------------------------------------------------------------
# 分割路径为两个部分:1.除最后路径外的全部路径    2.最后路径
result = os.path.split('C:/Users/Administrator/Desktop/os测试/python.txt')
print('{}'.format(result))

# 分割为:1.全部路径     2.文件格式后缀
result = os.path.splitext('C:/Users/Administrator/Desktop/os测试/python.txt')
print('{}'.format(result))

# 文件夹增删改操作-----------------------------------------------------
# 值1:修改前的名字
# 值2:修改后的名字
if os.path.exists('happy.txt'):
    os.rename('happy.txt', '葫芦娃.mp3')


# 删除文件    删除文件夹用removedirs
if os.path.exists('葫芦娃.mp3'):
    os.remove('葫芦娃.mp3')


# make directory
if os.path.exists('test'):
    pass
else:
    os.mkdir('test')



# 小程序:
# 1.随意输入一个数字  如果是1 创建一个文件夹 名字是test_one
# 2.如果是2 删除一个文件夹 名字是test_one
# 3.如果是其他数字 返回


import os
num = input('请输入你的数字:')
if num.isdigit():
    num = int(num)
    if num == 1:
        if os.path.exists('test_one'):
            pass
        else:
            os.mkdir('test_one')
    if num == 2:
        if os.path.exists('test_one'):
            os.removedirs('test_one')
        else:
            pass
    else:
        pass



    num = input('请输入你的数字:')
    if num.isdigit():
        num = int(num)
        if num == 1:
            if os.path.exists('test_one'):
                pass
            else:
                os.mkdir('test_one')
        if num == 2:
            if os.path.exists('test_one'):
                os.removedirs('test_one')
            else:
                pass
        else:
            pass


# change 改变 改变当前所在的目录
os.chdir('test')
print(os.getcwd())
# 改变路径到指定的路径下   pardir directory parent
os.chdir(os.path.pardir)
print('{}'.format(os.path.abspath('.')))
# os.chdir('test')
# print(os.getcwd())
# os.removedirs('testA')


# 文件读写-----------------------------------------------------
# 打开指定的文件  如果文件不存在,则创建
# w:write 写入    encoding 编码形式
# 写入时会将之前的内容清除掉
f = open('os.txt', 'w', encoding='utf-8')
f.write('Hello World\n')
f.write('你好\n')
f.writelines(['张三\n', '李四\n', '王五\n'])
f.close()

# 当文件关闭后  不能再继续对这个文件进行操作否则会报错 如下:
# f.write('几点开饭')
# ValueError: I/O operation on closed file.

# 小练习:
# 创建一个文件,名字为code.txt,在里面存放1万个六位随机数字的验证码
import random
f = open('code.txt', 'w', encoding='utf-8')
for x in range(10000):
    num = random.randint(0, 999999)
    num = '%.6d' % num
    f.write(num + '\n')
f.close()

f = open('code1.txt', 'w', encoding='utf-8')
for x in range(10000):
    content = ''
    for y in range(6):
        # 获取一个从0到9的数字
        num = random.randint(0, 9)
        # 将数字转化成字符,并和之前的字符拼接
        content += str(num)
    f.write(content + '\n')
f.close()

# r: read============================================================
f = open('code.txt', 'r', encoding='utf-8')
# content = f.read()
# print(content)
# content = f.read(22)
# print(content)
# 读一行
# content = f.readline()
# print(content)
# 将读出的结果 放入列表中
# content = f.readlines()
# print(content)




# 文件内容追加
f = open('new.txt', 'w', encoding='utf-8')
f.write('人生三大难:早上吃啥,中午吃啥,晚上吃啥\n')
f.close

# a:append 追加;添加
f = open('new.txt', 'a', encoding='utf-8')
f.write('啥都不想吃')
f.close

# 小练习
# 2.创建一个文件,里面存放10000个10位随机验证码  例如:asd8787aad
# 3.获取练习2中的文件,然后判断每个验证码中数字出现的次数
# 第二题 第一写法
import random
str1 = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0123456789"
f = open("old.txt", "w", encoding="utf-8")
for x in range(10000):
    result_str = ""
    for i in range(10):
        # random_str = random.choice(str1)   1.用choice()方法  从字符串str1中随机取1个字符
        # result += random_str                 将每个字符拼接在一起
        # random_str = random.sample(str1)   sample(a, b)方法  随机从目标字符串a里截取指定长度b的字符
        result_str += str1[random.randint(0,61)]
    f.write(result_str + '\n')
f.close()

# 第二题 第二写法
import random
str1 = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0123456789"
with open('random.txt', 'w', encoding='utf-8') as f:
    for index in range(10000):
        content = ''
        for x in range(10):
            # 如果对象是一个列表,元组或者字符串的时候,从这个对象中随机取出一块
            char_str = random.choice(str1)
            content += char_str
        f.write(content + '\n')
f.close()

# 第二题 第三写法
import random
str1 = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0123456789"
with open('random.txt', 'w', encoding='utf-8') as f:
    for index in range(10000):
        content = ''
        for x in range(10):
            char_str = str([random.randint(0, len(str1)-1)])
            content += char_str
        f.write(content + '\n')
f.close()




# 第三题 除写版
f = open("old.txt", "r", encoding="utf-8")
list1 = f.readlines()
for x in range(10000):
    ma_num = 0
    for ma in list1[x]:
        if ma.isdigit():
            ma_num += 1
        else:
            pass
    print('第{}个验证码出现了{}次数字'.format(x + 1, ma_num))
f.close()

# 统计所有验证码中每一个数字分别出现的总次数

# 简单版:
f = open('old.txt', 'r', encoding='utf-8')
list1 = f.readlines()
# count = 0
count0 = count1 = count2 = count3 = count4 = count5 = count6 = count7 = count8 = count9 = 0
for x in list1:
    # count0 = count1 = count2 = count3 = count4 = count5 = count6 = count7 = count8 = count9 = 0
    # count = 0
    for y in x:
        if y.isdigit():
            z = int(y)
            if z == 0:
                count0 += 1
            elif z == 1:
                count1+=1
            elif z == 2:
                count2+=1
            elif z == 3:
                count3+=1
            elif z == 4:
                count4+=1
            elif z == 5:
                count5+=1
            elif z == 6:
                count6 += 1
            elif z == 7:
                count7+=1
            elif z == 8:
                count8+=1
            else:
                count9+=1
        else:
            pass
print(count0, count1, count2, count3, count4, count5, count6, count7, count8, count9)
f.close()


# 困难版
import string
from random import randint

english = ''.join([string.ascii_lowercase, string.ascii_uppercase])
count = ''.join([str(i) for i in range(10)])
e_and_c = ''.join([count, english])
with open('aaa.txt', 'w') as f:
    for j in range(10000):
        st = ''.join([e_and_c[randint(0, len(e_and_c)-1)] for i in range(10)])
        f.write(''.join([st, ' ']))
    pass

with open('aaa.txt', 'r') as f:
    b = f.read()
dic = dict(zip([i for i in e_and_c], [b.count(i) for i in e_and_c]))
print(dic)
pass



# 适中版:
data = {}
for x in range(10):
    data[str(x)] = 0
print(data)
with open('old.txt', 'r', encoding='utf-8') as f:
    for line in f.readlines():
        for char in line:
            for key in data:
                if char == key:
                    data[key] += 1
print(data)


猜你喜欢

转载自blog.csdn.net/qq_35866413/article/details/80903060