how to read all files inside particular folder
using System.IO;
...
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
string contents = File.ReadAllText(file);
}
Note the above uses a .NET 4.0 feature; in previous versions replace EnumerateFiles
with GetFiles
). Also, replace File.ReadAllText
with your preferred way of reading xml files - perhaps XDocument
, XmlDocument
or an XmlReader
.
how to read all files in particular folder and filter more than one type?
You can concatenate two results like this
foreach (string file in Directory.EnumerateFiles(folderPath, "*.txt").Concat(Directory.EnumerateFiles(folderPath, "*.bmp")))
{
// (code here)
}
Or make it a function like so
IEnumerable<string> EnumerateFiles(string folderPath, params string[] patterns)
{
return patterns.SelectMany(pattern => Directory.EnumerateFiles(folderPath, pattern));
}
void Later()
{
foreach (var file in EnumerateFiles(".", "*.config", "*.exe"))
{
// (code here)
}
}
How to read all files in a folder from Java?
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
Files.walk API is available from Java 8.
try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}
The example uses try-with-resources pattern recommended in API guide. It ensures that no matter circumstances the stream will be closed.
How to read all files in a folder using C
You can use this sample code and modify it if you need:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
/* This is just a sample code, modify it to meet your need */
int main(int argc, char **argv)
{
DIR* FD;
struct dirent* in_file;
FILE *common_file;
FILE *entry_file;
char buffer[BUFSIZ];
/* Openiing common file for writing */
common_file = fopen(path_to_your_common_file, "w");
if (common_file == NULL)
{
fprintf(stderr, "Error : Failed to open common_file - %s\n", strerror(errno));
return 1;
}
/* Scanning the in directory */
if (NULL == (FD = opendir (in_dir)))
{
fprintf(stderr, "Error : Failed to open input directory - %s\n", strerror(errno));
fclose(common_file);
return 1;
}
while ((in_file = readdir(FD)))
{
/* On linux/Unix we don't want current and parent directories
* On windows machine too, thanks Greg Hewgill
*/
if (!strcmp (in_file->d_name, "."))
continue;
if (!strcmp (in_file->d_name, ".."))
continue;
/* Open directory entry file for common operation */
/* TODO : change permissions to meet your need! */
entry_file = fopen(in_file->d_name, "rw");
if (entry_file == NULL)
{
fprintf(stderr, "Error : Failed to open entry file - %s\n", strerror(errno));
fclose(common_file);
return 1;
}
/* Doing some struf with entry_file : */
/* For example use fgets */
while (fgets(buffer, BUFSIZ, entry_file) != NULL)
{
/* Use fprintf or fwrite to write some stuff into common_file*/
}
/* When you finish with the file, close it */
fclose(entry_file);
}
/* Don't forget to close common file before leaving */
fclose(common_file);
return 0;
}
Hope this hellp.
Regards.
Read all files in specific folder in R
Set your base directory, and then use it to create a vector of all the files with list.files
, e.g.:
base_dir <- 'path/to/my/working/directory'
all_files <- paste0(base_dir, list.files(base_dir, recursive = TRUE))
Then just loop over all_files
. By default, list.files
has recursive = FALSE
, i.e., it will only get the files and directory names of the directory you specify, rather than going into each subfolder. Setting recursive = TRUE
will return the full filepath excluding your base directory, which is why we concatenate it with base_dir
.
How to open every file in a folder
Os
You can list all files in the current directory using os.listdir
:
import os
for filename in os.listdir(os.getcwd()):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Glob
Or you can list only some files, depending on the file pattern using the glob
module:
import os, glob
for filename in glob.glob('*.txt'):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
It doesn't have to be the current directory you can list them in any path you want:
import os, glob
path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Pipe
Or you can even use the pipe as you specified using fileinput
import fileinput
for line in fileinput.input():
# do your stuff
And you can then use it with piping:
ls -1 | python parse.py
(C#) How to read all files in a folder to find specific lines?
Start with
const string lineToFind = "blah-blah";
var fileNames = Directory.GetFiles(@"C:\path\here");
foreach (var fileName in fileNames)
{
int line = 1;
using (var reader = new StreamReader(fileName))
{
// read file line by line
string lineRead;
while ((lineRead = reader.ReadLine()) != null)
{
if (lineRead == lineToFind)
{
Console.WriteLine("File {0}, line: {1}", fileName, line);
}
line++;
}
}
}
As Nick pointed out below, you can make search parallel using Task Library, just replace 'foreach' with Parallel.Foreach(filesNames, file=> {..});
Directory.GetFiles: http://msdn.microsoft.com/en-us/library/07wt70x2
StreamReader: http://msdn.microsoft.com/en-us/library/f2ke0fzy.aspx
Related Topics
Convert String to Hex-String in C#
Mvvm Light 5.0: How to Use the Navigation Service
Linq Order by Null Column Where Order Is Ascending and Nulls Should Be Last
Dependency Injection Using Azure Webjobs Sdk
Copy Rows from One Datatable to Another Datatable
How to Convert Datetime To/From Specific String Format (Both Ways, E.G. Given Format Is "Yyyymmdd")
Check If the Current User Is Administrator
Access to Foreach Variable in Closure Warning
Send Smtp Email Using System.Net.Mail via Exchange Online (Office 365)
How to Show File Copy Progress Using Fileinfo.Copyto() in .Net
Entity Framework/Sql2008 - How to Automatically Update Lastmodified Fields for Entities
Convert Base Class to Derived Class
Is Endinvoke() Optional, Sort-Of Optional, or Definitely Not Optional
How to Initialize a List<T> to a Given Size (As Opposed to Capacity)