c/c++/python 文件夹文件名读取并写txt

(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++代码还是比较简单的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值