import random
import os
import numpy as np
# A文件夹:
i = 0
while i < 1000: # 该过程执行1000遍
ran1 = np.round(random.random(), 4) # 随机生成一个浮点数,保留4位小数
if ran1 < 0.5:
ran1 = ran1 * 1000 # 该数乘以1000
a = "%03d" % ran1 # 规定四位数格式,str类型
file_name1 = str('A_' + a + '_AA')
if (not os.path.exists("C:/Users/34163/Desktop/A/" + file_name1 + '.txt')):
f = open("C:/Users/34163/Desktop/A/" + file_name1 + '.txt', "w", encoding="UTF-8")
f.write(str(ran1) + '\n')
f.close()
# 判断文件是否已经存在
else:
g = open("C:/Users/34163/Desktop/A/" + file_name1 + '.txt', "a", encoding="UTF-8")
g.write(str(ran1) + '\n')
g.close()
i = i + 1
# B文件夹:
j = 0
while j < 1000: # 该过程执行1000遍
ran2 = np.round(random.random(), 4) # 随机生成一个浮点数,保留4位小数
if ran2 < 0.5:
ran2 = ran2 * 1000 # 该数乘以1000
# c = "%03d" % ran2 # 规定四位数格式,str类型
c = str(int(ran2)).zfill(3)
# 注意先将ran2变成int类型,如果浮点类型超出zfill()的范围则函数无效
# zfill(num)函数只能对字符串进行操作,num为保留位数,不够在前面加0,超出范围则并作出变化,保持原来的字符串
file_name2 = str('B_' + c + '_BB')
if (not os.path.exists("C:/Users/34163/Desktop/B/" + file_name2 + '.txt')):
h = open("C:/Users/34163/Desktop/B/" + file_name2 + '.txt', "w", encoding="UTF-8")
h.write(str(ran2) + '\n')
h.close()
# 判断文件是否已经存在
else:
k = open("C:/Users/34163/Desktop/B/" + file_name2 + '.txt', "a", encoding="UTF-8")
k.write(str(ran2) + '\n')
k.close()
j = j + 1
(2)查找给出A和B文件夹中,随机数部分相同的文件名,并输出。
a = r'C:\Users\34163\Desktop\A'
b = r"C:\Users\34163\Desktop\B"
list_A_name = os.listdir(a)
list_B_name = os.listdir(b)
A_ran = [] # 用于存放A文件名中的随机数
B_ran = [] # 用于存放B文件名中的随机数
# 定义函数用于提取文件名中的随机数
def trans(list, ran):
x = 0
while x < len(list):
ran_list = list[x].split("_")
ran.append(ran_list[-2])
x = x + 1
print(ran)
trans(list_A_name, A_ran) # 调用函数得到A文件名中的随机数
trans(list_B_name, B_ran) # 调用函数得到B文件名中的随机数
y = 0
# 判断A文件夹中文件名的随机数是否在B中也存在
for A_ran[y] in A_ran:
if A_ran[y] in B_ran:
print("C:/Users/34163/Desktop/A/A_" + A_ran[y] + '_AA.txt')
print("C:/Users/34163/Desktop/B/B_" + A_ran[y] + '_BB.txt')
y = y + 1
(3)分别查找A和B文件夹中,写入行数大于1的文件名。
提示:使用random,split,append等函数。
A = "C:/Users/34163/Desktop/A/" # A文件夹路径
B = "C:/Users/34163/Desktop/B/" # B文件夹路径
list_A_name = os.listdir(A)
list_B_name = os.listdir(B)
def find(list_name, option):
x = 0
while x < len(list_name):
with open(option + list_name[x], "r", encoding="utf-8") as s:
lines = s.readlines()
count = 0
flag = False # 标志写入行数大于1的文件名
for line in lines:
print(line)
count = count + 1
if count > 1:
flag = True
if flag == True:
print(option + list_name[x], '\n', '*' * 50)
x = x + 1
find(list_A_name, A)
find(list_B_name, B)