㈠ python 把文件內容讀到一個數組里
首先py的數組使用列表代替的,除非py的擴展工具包,比如py有一個支持矩陣的包裡面有數組的概念,
將文件讀到列表裡:
f = open('file_name.txt','r')
f_list = f.readlines()
可以print(f_list)查看列表,這是將文件的所有內容一次性讀到列表中
㈡ c語言 讀取目錄中的文件名,並將其存入數組中
用system 調用 DOS DIR 命令就可以了:
system ( "dir sss_* /B > log.txt");
這就把 前綴為sss_的文件 文件名 存入 log.txt 文件了。
一個名字一行,沒有別的東西。
你再 讀出來。
#include <stdio.h>
main()
{
FILE *fp;
char str[30][50]; // 假定文件數不超過30個
int i,n=0;
system("dir sss_* /B > log.txt");
fp=fopen("log.txt","r");
while(1){
if ( fgets(str[n],50,fp)==NULL) break;
str[n][strlen(str[n])-1]='\0'; // 加一個字元串結束符
n++;
}
fclose(fp);
for (i=0;i<n;i++) printf("%s\n",str[i]);
}
㈢ c++中怎麼把讀取文件夾下的所有文件名存入數組
1、在linux平台,可採用目錄操作函數,讀取當前目錄下的文件
#include <sys/types.h>
#include <dirent.h> //windows開發工具沒有這個頭文件
#include <unistd.h>
#include <string.h>
main()
{
DIR * dir;
struct dirent * ptr;
char file_list[100][40];
int i=0;
dir = opendir("/etc/rc.d"); //打開一個目錄
while((ptr = readdir(dir)) != NULL) //循環讀取目錄數據
{
printf("d_name : %s\n", ptr->d_name); //輸出文件名
strcpy(file_list[i],ptr->d_name ); //存儲到數組
if ( ++i>=100 ) break;
}
closedir(dir);//關閉目錄指針
}
2、在windows平台下,如VC也有類似的操作函數,如:
#include <string>
#include <iostream>
using namespace std;
#include <WINDOWS.H>
void main()
{
string szPath="d:/*.*";
WIN32_FIND_DATA wfd;
HANDLE hFind;
char file_list[100][40];
int i=0;
hFind = FindFirstFile(szPath.c_str(), &wfd) ;
do
{
cout << wfd.cFileName << endl ;
strcpy(file_list[i],wfd.cFileName ); //存儲到數組
if ( ++i>=100 ) break;
}while (FindNextFile(hFind, &wfd));
FindClose(hFind);
}
㈣ VB/Script 怎樣讀取一個目錄下的所有文件名到數組
你可以使用opendir, closedir and readdir 這三種方法例如:
opendir DIR, $dir or die "cannot open dir $dir: $!";
my @file= readdir DIR;
closedir DIR;
㈤ C語言如何讀取TXT文件並存入數組中
一、編程思路。
1 以文本方式打開文件。
2 循環用fscanf格式化輸入數據到數組。
3 判斷fscanf的返回值,如果顯示到達文件結尾,退出輸入。
4 關閉文件。
5 使用數據。
二、代碼實現。
設定文件名為in.txt, 存有一系列整型數據,以空格或換行分隔。
代碼可以寫作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
int main()
{
int v[100];//開一個足夠大的數組。
int i = 0, j;
FILE *fp;//文件指針
fp = fopen("in.txt", "r");//以文本方式打開文件。
if(fp == NULL) //打開文件出錯。
return -1;
while(fscanf(fp, "%d", &v[i]) != EOF) //讀取數據到數組,直到文件結尾(返回EOF)
i++;
fclose(fp);//關閉文件
for(j = 0; j < i; j ++)//循環輸出數組元素。
{
printf("%d ", v[j]);
}
return 0;
}
當文件內容為:
1 35 6 8 9 9
10 123 34
76 54 98
程序輸出:
1 35 6 8 9 9 10 123 34 76 54 98