How can I iterate over files in a given directory?
Python 3.6 version of the above answer, using os
- assuming that you have the directory path as a str
object in a variable called directory_in_str
:
import os
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".asm") or filename.endswith(".py"):
# print(os.path.join(directory, filename))
continue
else:
continue
Or recursively, using pathlib
:
from pathlib import Path
pathlist = Path(directory_in_str).glob('**/*.asm')
for path in pathlist:
# because path is object not string
path_in_str = str(path)
# print(path_in_str)
- Use
rglob
to replaceglob('**/*.asm')
withrglob('*.asm')
- This is like calling
Path.glob()
with'**/'
added in front of the given relative pattern:
- This is like calling
from pathlib import Path
pathlist = Path(directory_in_str).rglob('*.asm')
for path in pathlist:
# because path is object not string
path_in_str = str(path)
# print(path_in_str)
Original answer:
import os
for filename in os.listdir("/path/to/dir/"):
if filename.endswith(".asm") or filename.endswith(".py"):
# print(os.path.join(directory, filename))
continue
else:
continue
How to iterate over all files in multiple folders with python
You can use the below sample snippet both #1 or #2 works:
import os
path = "."
for (root, dirs, files) in os.walk(path, topdown=True):
for file in files:
if file.endswith(".html"):
print(root+"/"+file) #1
print(os.path.join(root+"/"+file)) #2
How can I iterate over all files in all folders of one master folder?
You can use os.walk()
import os
path = 'c:\\projects\\hc2\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.txt' in file:
files.append(os.path.join(r, file))
for f in files:
print(f)
Output:
c:\projects\hc2\app\readme.txt
c:\projects\hc2\app\release.txt
c:\projects\hc2\web\readme.txt
c:\projects\hc2\whois\download\afrinic.txt
c:\projects\hc2\whois\download\apnic.txt
c:\projects\hc2\whois\download\arin.txt
c:\projects\hc2\whois\download\lacnic.txt
c:\projects\hc2\whois\download\ripe.txt
c:\projects\hc2\whois\out\test\resources\asn\afrinic\3068.txt
c:\projects\hc2\whois\out\test\resources\asn\afrinic\37018.txt
Write code to iterate all files in a directory and append each file's path to a dictionary
I changed files_dir = {}
line to
files_in_dir = { key:0 for key in os.listdir(args.source_dir) if os.path.abspath(key).endswith(".csv") }
and it seems work.if-else in for statement version following requests:
for key in os.listdir(args.source_dir):
if os.path.abspath(key).endswith(".csv"):
files_in_dir[key] = 0
else:
print(f"The file {key} is not a .csv file and it will be ignored")
How do I iterate through all files inside a given directory and create folders and move the file?
Try this:
import os
import shutil
path = r"C:\Users\vasudeos\OneDrive\Desktop\newfolder"
for x in os.listdir(path):
file = os.path.join(path, x)
if not os.path.isdir(file):
folder_name = os.path.join(path, os.path.splitext(x)[0])
if not os.path.exists(folder_name):
os.mkdir(folder_name)
shutil.move(file, folder_name)
Iterate all files in a directory using a 'for' loop
This lists all the files (and only the files) in the current directory and its subdirectories recursively:
for /r %i in (*) do echo %i
Also if you run that command in a batch file you need to double the % signs.
for /r %%i in (*) do echo %%i
(thanks @agnul)
How do I iterate through the files in a directory and it's sub-directories in Java?
You can use File#isDirectory()
to test if the given file (path) is a directory. If this is true
, then you just call the same method again with its File#listFiles()
outcome. This is called recursion.
Here's a basic kickoff example:
package com.stackoverflow.q3154488;
import java.io.File;
public class Demo {
public static void main(String... args) {
File dir = new File("/path/to/dir");
showFiles(dir.listFiles());
}
public static void showFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getAbsolutePath());
showFiles(file.listFiles()); // Calls same method again.
} else {
System.out.println("File: " + file.getAbsolutePath());
}
}
}
}
Note that this is sensitive to StackOverflowError
when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk()
instead which utilizes tail recursion:
package com.stackoverflow.q3154488;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DemoWithJava8 {
public static void main(String... args) throws Exception {
Path dir = Paths.get("/path/to/dir");
Files.walk(dir).forEach(path -> showFile(path.toFile()));
}
public static void showFile(File file) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getAbsolutePath());
} else {
System.out.println("File: " + file.getAbsolutePath());
}
}
}
Related Topics
Uploading Multiple Files With Paperclip
One-Liner to Recursively List Directories in Ruby
Extract Number from String in Ruby
Rails Engines Extending Functionality
Why Is Sudo: Bundle Command Not Found
Setting Up Rake-Pipeline for Use with Handlebars Alongside Google App Engine
Ruby Array Subtraction Without Removing Items More Than Once
What Is Causing This Activerecord::Readonlyrecord Error
Nested Models and Parent Validation
Using Www:Mechanize to Download a File to Disk Without Loading It All in Memory First
How to Get Filename Without Extension from File Path in Ruby
In Rails, How to Add a New Method to String Class
How to Run All Tests With Minitest
Execute a Sudo Command in Ruby on Rails App
Is This the Best Way to Unescape Unicode Escape Sequences in Ruby