其他分享
首页 > 其他分享> > 实验六 文件应用编辑-2

实验六 文件应用编辑-2

作者:互联网

Task——3

def is_valid(x):
    if len(x) != 18 :
        return False
    else:
        for i in x:
            if '0'<=i<='9'or i=='X':
                continue
            return False
        else:
            return True

import csv
import random
with open('data3_id.txt','r',encoding='utf-8')as f:
    data = f.readlines()
data = [line.strip().split(',') for line in data]
list1 = []
for i in range(1,len(data)):
    if(is_valid(data[i][1])):

        list1.append([data[i][0],data[i][1][6:10]+'-'+data[i][1][10:12]+'-'+data[i][1][12:14]])
list1.sort(key=lambda x:x[1])
print(f'{data[0][0]},{data[0][1]}')
for line in list1:
    print(f'{line[0]},{line[1]}')

 

 

task 5.1

import random
import datetime
n = int(input("输入随机抽点人数: "))
with open("data5.txt", encoding="utf-8") as f:
    data = f.readlines()
data1 = data.copy()
people = []
for i in range(n):
    x = random.choice(data1)
    people.append(x)
    data1.remove(x)

t = datetime.datetime.now()
filename = t.strftime('%Y%m%d') + '.txt'
with open(filename, "w+", encoding="utf-8") as f:
    f.writelines(people)
    f.seek(0)
    print(f.read())

task 5.2

import random
import datetime
t = datetime.datetime.now()
filename = t.strftime('%Y%m%d') + '.txt'


print("{0:{1}{3}{2}}".format("抽点开始", "=", 40, "^"))

ls = []
while True:
    n = int(input("输入随机抽点人数: "))
    if n == 0:
        break
    else:
        with open("data5.txt", encoding="utf-8") as f:
            data = f.readlines()
        data1 = data.copy()
        people = []
        for i in range(n):
            x = random.choice(data1)
            people.append(x)
            data1.remove(x)
        with open(filename, "w+", encoding="utf-8") as f:
            f.writelines(people)
            f.seek(0)
            print(f.read())
    ls += people
with open(filename, "w", encoding="utf-8") as f:
    f.writelines(ls)
print("{0:{1}{3}{2}}".format("抽点结束", "=", 40, "^"))

总结

此次实践让我对于文件编辑,能更熟练的操作,学到了更多不同的操作方式

通过random,datetime模块能更简单的完成任务。

标签:文件,random,people,open,encoding,datetime,编辑,实验,data1
来源: https://www.cnblogs.com/haze529/p/16303775.html