Part 01 批量读取文件名,并将读取的文件名保存到指定路径下的txt中(带.*** 后缀
# P01 批量读取文件名,并将读取的文件名保存到指定路径下的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 = "C:/本地路径/JPEGImages" # 读取文件路径
outfile = "Image.txt" # 将文件名写入Image.txt
wildcard = ".jpg" # 读取jpg图片
# wildcard = ".jpg .txt .exe .dll .lib" #要读取的文件类型;
file = open(outfile, "w")
if not file:
print("cannot open the file %s for writing" % outfile)
ListFilesToTxt(dir, file, wildcard, 1)
file.close()
ReadName()
Part 02 只读取文件名,并将读取的文件名保存到指定路径下的txt中(不带文件后缀)
# P02 批量读取文件名(不带后缀)
import os
file_path = "C:/本地路径/Image/"
path_list = os.listdir(file_path) # os.listdir(file)会历遍文件夹内的文件并返回一个列表
print(path_list)
path_name = [] # 把文件列表写入save.txt中
def saveList(pathName):
for file_name in pathName:
with open("Image.txt", "a") as f:
f.write(file_name.split(".")[0] + "\n")
def dirList(path_list):
for i in range(0, len(path_list)):
path = os.path.join(file_path, path_list[i])
if os.path.isdir(path):
saveList(os.listdir(path))
dirList(path_list)
saveList(path_list)
Part 03在txt文件中,在读取的文件名前批量添加 前缀/ 后缀
# P03批量添加 ****/ 前缀
import pandas as pd
data = pd.read_csv("C:/本地路径/Image.txt", header=None); # 读取需要修改的文件
print(data)
for i in range(len(data)):
data.iloc[i] = 'data/obj/' + data.iloc[i] # 加上 data/obj/ 前缀
print(data.iloc[i])
data.to_csv('./addSuffixImage.txt', index=None)