(1) c/c++ 代码
查找文件夹下所有文件,借鉴链接https://blog.csdn.net/CSDNwei/article/details/76619178。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <Windows.h>
using namespace std;
void find(char* lpPath, std::vector<const std::string> &fileList)
{
char szFind[MAX_PATH];
WIN32_FIND_DATA FindFileData;
strcpy(szFind, lpPath);
strcat(szFind, "\\*.*");
HANDLE hFind = ::FindFirstFile(szFind, &FindFileData);
if (INVALID_HANDLE_VALUE == hFind) return;
while (true)
{
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (FindFileData.cFileName[0] != '.')
{
char szFile[MAX_PATH];
strcpy(szFile, lpPath);
strcat(szFile, "\\");
strcat(szFile, (char*)(FindFileData.cFileName));
find(szFile, fileList);
}
}
else
{
//std::cout << FindFileData.cFileName << std::endl;
fileList.push_back(FindFileData.cFileName);
}
if (!FindNextFile(hFind, &FindFileData)) break;
}
FindClose(hFind);
}
写文件:
ofstream fwrite("e:/TXT/train1.txt", 'w');
fwrite.open("e:/TXT/train1.txt", ios::app);
string picFullName = (fullName + "/" + fileName);
fwrite << picFullName << ' ' << index << ' ' << num << "\n";
fwrite.close();
主要是关于写文件流的几个写入方式以及最好打开之后写再关闭。
2.python 文件读写
fopen=open(txtName,'w+')
index=0
for name in listName:
picLoc = path + '\\' + name + '\\'
index+=1
# 子文件夹下面所有的有对应TXT的图片
dirName = os.listdir(picLoc)
for f in dirName:
if f.endswith('.jpg'):
picTxtName = f[:-3]
picTxtName+='txt'
if os.path.exists(picLoc+'\\'+picTxtName):
f=picLoc+'\\'+f
fopen.write(f+"\t"+str(index)+"\t0\n")
fopen.close()
python 相比较c++代码还是比较简单的。