1、读取文件名称生成txt文件
import os
def ListFilesToTxt(dir, file, wildcard, recursion):
exts = wildcard.split(" ")
files = os.listdir(dir)
for name in files:
fullname = os.path.join(dir, name)
if (os.path.isdir(fullname) & recursion):
ListFilesToTxt(fullname, file, wildcard, recursion)
else:
for ext in exts:
if (name.endswith(ext)):
file.write(name + "\n")
break
def ReadName():
dir = "F:/1.Research/2022/Tensorflow/class4/MNIST_FC//mnist_image_label/mnist_test_jpg_10000"
outfile = "F:/1.Research/2022/Tensorflow/class4/MNIST_FC//mnist_image_label/Image1.txt"
wildcard = ".jpg"
file = open(outfile, "w")
if not file:
print("cannot open the file %s for writing" % outfile)
ListFilesToTxt(dir, file, wildcard, 1)
file.close()
ReadName()
借鉴:https:///GeekYao/article/details/105074574
运行结果:
在import re
read_txt = open("F:/1.Research/2022/Tensorflow/class4/MNIST_FC/mnist_image_label/Image1.txt", "r", encoding="utf-8")
temp = []
for line in read_txt:
b = re.findall(r'[_](.*?)[.]', line)
'''
print(a)
输出结果:
['1/902', '0.079s']
['2/902', '0.015s']
['3/902', '0.015s']
要提取的内容在列表的第二个索引中,再去掉a[1]中的s
'''
'''
print(b)
输出结果:
['0.079']
['0.015']
['0.015']
要提取的内容在列表的第一个索引中,注意不是列表b呦。。。
'''
temp.append((b[0]))
'''
print(temp)
输出内容:
['0.079']
['0.079', '0.015']
['0.079', '0.015', '0.015']
循环一次添加一个,最后得到我们要的列表。。。。
对一个python小白来说搞到这里好艰难,参考网友的内容,一点点的搞出来了。。。。。
还有最后一步,保存到文件。。。
'''
with open("train1.txt", "w", encoding='utf-8') as file:
for i in temp:
file.write(i + '\n')
file.close()
'''trian文件内容'''
运行结果:
f_ = open('F:/1.Research/2022/Tensorflow/class4/MNIST_FC/mnist_image_label/Image1.txt', 'r')
n = 0
list1 = []
for i in f_.readlines():
n += 1
s = i.strip()
list1.append(s)
f_.close()
ff_ = open('F:/1.Research/2022/Tensorflow/class4/MNIST_FC/mnist_image_label/train1.txt', 'r')
m = 0
list2 = []
for i in ff_.readlines():
m += 1
s = i.strip()
list2.append(s)
ff_.close()
fff_ = open('Merge1.txt', 'w')
for i in range(n):
s = list1[i] + ' ' + list2[i]
fff_.write(s + '\n')
fff_.close()
运行结果: