I have a text file containing directory names on each line (1, 2, 3), how can I iterate through the text file and have the result inserted into os.walk?
So far, I have
import os
from os import listdir
dir_file = open("list.txt", "r")
for root, dirs, files in os.walk(dir_file):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
I have used a combination of while loops and for loops and if statements to try and perform this, but I've had no luck.
Any help?
Thanks
How about:
rdf = []
for fff in dir_file:
for r, d, f in os.walk(fff):
rdf.append(r, d, f)
I resolved this issue with:
import os
from os import listdir
dir_file = open("list.txt", "r")
for x in dir_file:
for root, dirs, files in os.walk(x.strip()):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
Thanks :)
Related
I want to get my script to read a list of names from a list(txt), then search for those in a selected folder with subfolders, then copy and paste those files to another selected folder. My script running without error but no result.
My script:
import os
import os.path
import shutil
textFile = ("D:\\Test\\list.txt")
sourceFolder = ("D:\\Test")
destinationFolder = ("D:\\")
filesToFind = []
with open(textFile, "r") as tx:
for row in tx:
filesToFind.append(row.strip())
for root, dirs, filename in os.walk(sourceFolder):
if filename in filesToFind:
f = os.path.join(root, filename)
shutil.copy(f, destinationFolder)
Haven’t test it but I think this will work - change this:
for root, dirs, filename in os.walk(sourceFolder):
if filename in filesToFind:
f = os.path.join(root, filename)
shutil.copy(f, destinationFolder)
To this:
for root, dirs, filenames in os.walk(sourceFolder):
for filename in filenames:
if filename in filesToFind:
f = os.path.join(root, filename)
shutil.copy(f, destinationFolder)
# Same code using glob #
## More efficient and also tested one ##
## One more feature added- checks file name given present or not ##
import os
import os.path
import shutil
import glob
textFile = ("D:\\Test\\list.txt")
sourceFolder = ("D:\Test")
destinationFolder = ("D:\\")
f = open(textFile, "r").readlines()
for i in f:
ListFile= glob.glob(os.path.join(sourceFolder,"**",i.strip()),recursive=True)
if len(ListFile):
print(ListFile[0],destinationFolder,os.path.basename(ListFile[0]))
destinationfile=os.path.join(destinationFolder,os.path.basename(ListFile[0]))
shutil.copyfile(ListFile[0],destinationfile)
else:
print(i,"-File not found")
I have some textfiles in a folder and I want to search all of them for names between row 4 and 20 and then copy the ones containing one of those names to a different folder. With my code I only get an empty result file even though I know the keywords are in my folder. What could be the problem with this code for Python 3?
from os import system, listdir, path
import codecs
FILE = open('C:\\Users\\Admin\\Desktop\\Test\\Result.txt', 'w')
desktop_dir = path.join('C:\\Users\\Admin\\Desktop\\test\\')
for fn in listdir(desktop_dir):
fn_w_path = path.join(desktop_dir, fn)
if path.isfile(fn_w_path):
with open(fn_w_path, "r") as filee:
for line in filee.readlines():
for word in line.lower().split():
if word in {'James',
'Tim',
'Tom',
'Ian',
'William',
'Dennis',}:
FILE.write(word + "\n")
FILE.close()
import os
import shutil
for root, dirs, files in os.walk("test_dir1", topdown=False):
for name in files:
current_file = os.path.join(root, name)
destination = current_file.replace("test_dir1", "test_dir2")
print("Found file: %s" % current_file)
print("File copy to: %s" % destination)
shutil.copy(current_file, destination)
Lets say the directories hierarchy looks like this:
A(root)
|
B---------C--------D
| | |
fileB.h fileC.png fileD.py
fileC1.jpg
E
|
fileE.py
How can I access all the doc? Or just get the path. Is there a way to iterlate all?
What I do:
path = sys.path[0]
for filename_dir in os.listdir(path):
filename, ext = os.path.splitext(filename_dir)
if ext == '.h':
#do something
elif ext == '.png'
#do something
.....
But as I know listdir can only access the directory where my program's py file located.
This gives only the dirs and files under a directory, but not recursively:
import os
for filename in os.listdir(path):
print filename
If you want to list absolute paths:
import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
If you want resursive search, this gives you an iterator that returns 3-tuples including the parent directory, list of directories, and list of files at each iteration:
for i,j,k in os.walk('.'):
print i, j, k
For example:
import os
path = sys.path[0]
for dirname, dirnames, filenames in os.walk(path):
for subdirname in dirnames:
print "FOUND DIRECTORY: ", os.path.join(dirname, subdirname)
for filename in filenames:
print "FOUND FILE: ", os.path.join(dirname, filename)
I try to put a listing of subdirectories of a directory into a list.
I use that code :
import os
for dirname, dirnames, filenames in os.walk("W:/test"):
# print path to all subdirectories first.
for subdirname in dirnames:
a= os.path.join(dirname, subdirname)
liste = []
liste.append(a)
print liste
The problem is that I have not all my subdirectories into my list "liste"
Would you have any solutions ?
Thanks
You need to call liste.append inside the loop.
import os
liste = []
for root, dirs, files in os.walk(path):
for subdir in dirs:
liste.append(os.path.join(root, subdir))
print(liste)
I want to return the path of a file, If it is found by the program, but I want it to continue to loop(or recursively repeat) the program until all files are checked.
def findAll(fname, path):
for item in os.listdir(path):
n = os.path.join(path, item)
try:
findAll(n, fname)
except:
if item == fname:
print(os.idontknow(item))
So I'm having trouble with calling the path, right now I have
os.idontknow(item)
as a place holder
Input is :
findAll('fileA.txt', 'testpath')
The output is:
['testpat\\fileA.txt', 'testpath\\folder1\\folder11\\fileA.txt','testpath\\folder2\\fileA.txt']
Per my comment above, here is an example that will start at the current directory and search through all sub-directories, looking for files matching fname:
import os
# path is your starting point - everything under it will be searched
path = os.getcwd()
fname = 'file1.txt'
my_files = []
# Start iterating, and anytime we see a file that matches fname,
# add to our list
for root, dirs, files in os.walk(path):
for name in files:
if name == fname:
# root here is the path to the file
my_files.append(os.path.join(root, name))
print my_files
Or as a function (more appropriate for your case :) ):
import os
def findAll(fname, start_dir=os.getcwd()):
my_files = []
for root, dirs, files in os.walk(start_dir):
for name in files:
if name == fname:
my_files.append(os.path.join(root, name))
return my_files
print findAll('file1.txt')
print findAll('file1.txt', '/some/other/starting/directory')
Something like this, maybe?
import os
path = "path/to/your/dir"
for (path, dirs, files) in os.walk(path):
print files