Using Python, I want to print all the files inside a given directory, without display the directory itself. I tried to use os.walk but it always print the directory.
for root, dirs, files in os.walk(directory):
for subFile in files:
print os.path.join(root, subFile)
I used the directory 'DummyFolder/testFolder'
It prints:
DummyFolder/testFolder/folder1/folder2/file.txt
DummyFolder/testFolder/folder1/folder2/file2.txt
DummyFolder/testFolder/folder3/file3.txt
I want it to print:
folder1/folder2/file.txt
folder1/folder2/file2.txt
folder3/file3.txt
How can it be done?
Thanks!
Use os.path.relpath to get path relative to your directory.
print(os.path.relpath(os.path.join(root, subFile), directory))
Related
I am trying to zip all the files and folders present in a folder3 using python.
I have used zipFile for this. The zip contains all the folders from the root directory to the directory I want to create zip folder of.
def CreateZip(dir_name):
os.chdir(dir_name)
zf = zipfile.ZipFile("temp.zip", "w")
for dirname, subdirs, files in os.walk(dir_name):
zf.write(dirname)
for filename in files:
file=os.path.join(dirname, filename)
zf.write(file)
zf.printdir()
zf.close()
Expected output:
toBeZippedcontent1\toBeZippedFile1.txt
toBeZippedcontent1\toBeZippedFile2.txt
toBeZippedcontent1\toBeZippedFile1.txt
toBeZippedcontent2\toBeZippedFile2.txt
Current output (folder structure inside zip file):
folder1\folder2\folder3\toBeZippedcontent1\toBeZippedFile1.txt
folder1\folder2\folder3\toBeZippedcontent1\toBeZippedFile2.txt
folder1\folder2\folder3\toBeZippedcontent2\toBeZippedFile1.txt
folder1\folder2\folder3\toBeZippedcontent2\toBeZippedFile2.txt
walk() gives absolute path for dirname so join() create absolut path for your files.
You may have to remove folder1\folder2\folder3 from path to create relative path.
file = os.path.relpath(file)
zf.write(file)
You could try to slice it
file = file[len("folder1\folder2\folder3\\"):]
zf.write(file)
but relpath() should be better.
You can also use second argument to change path/name inside zip file
z.write(file, 'path/filename.ext')
It can be useful if you run code from different folder and you don't use os.chdir() so you can't create relative path.
I need to print a list of all files in sub-directories of the directory "H:\Reference_Archive\1EastRefsJan2014". I am currently using the code:
for root, dirs, files in os.walk("H:\Reference_Archive\1EastRefsJan2014"):
for name in files:
print os.path.join(root, name)
The code works and I get a long list of files if I run it only on the root directory ("H:\Reference_Archive"), but when I try to run it on the sub-directory as it is written above, nothing is returned or printed. The path that is written above contains several more sub-directories which all contain files. I have double checked that I have the pathway correct.
try this, you omitted dirs
for root, dirs, files in os.walk("H:\Reference_Archive\1EastRefsJan2014"):
for name in files:
print os.path.join(root, name)
Finally figured out that the os.walk function was not working with my folder because the folder name started with a number. Once I changed the name of the folder, it worked properly.
I know there are a lot of questions related to this, but I can't seem to find an answer that helps me solve the problem.
I'm using os.walk() to loop through subfolders in my main folder, which contains both folders and files.
Main Folder
Pass Folder
files.txt
Fail Folder
files.txt
file.txt
file2.txt
So I'm using this code to create a new text file based on the subfolder names. However this returns folder/.txt, which means that dirs is returning '/' and files is returning ['file.txt', 'file2.txt'].
for root, dirs, files in os.walk(path):
for dirs in root:
new_txt = 'folder%s.txt' % (dirs)
How do fix it so that dirs returns ['Main Folder/Pass Folder', 'Main Folder/Fail Folder'] and files returns the files in each folder?
I used something similar to this in my code recently (which, if I recall correctly, I also found on SO). Mine went something like this:
for (dirpath, subdirs, filelist) in os.walk(folder):
# join directories in here
From the documentation:
dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).
I'm not sure os.walk() does quite what you expect. I would suggest joining the directories together using os.path.join() to get what you want.
I am trying to read some file which is inside some specific directory like.
I am trying to use python2.7+ version. Here is my requirements like:
Find directory starts with B1234 (here 1234 is nr) inside output folder
if directory exists then goto directories starting with only TEST_
read only file endswith YYYY.txt
but that can reside inside subdirectory (name is not important here)
I am trying to make following code working but in vain
for root, dirs, files in os.walk('output'):
for file in files:
if file.startswith('test') and file.endswith('_YYYY.txt'):
try:
f = open(os.path.abspath(os.path.join(root,file)) , 'r')
except:
print 'oops'
Problem is here I can find all desired files but also from unwanted directories..
i would like to use like that
for dir in dirList:
if dir startswith(B1234)
for testdir in os.listdir(dir)
if dir.startswiht(TEST_)
goto dir
search for file
Any help will be appreciable..please askif you need more info:
I think you need to make the change here :
for root, dirs, files in os.walk('output'):
for dir in dirs:
if dir.startswith('B1234') is False:
continue
for r, drs, fls in os.walk(dir):
# now write your code here
So I let a user to set a path to a directory that may contain subdirectories (more levels), and files.
I use os.walk() in my code to scan the whole directory:
for root, subdirs, files in os.walk(thispath):
for myfile in files:
shutil.move(os.path.realpath(myfile), os.path.join(thispath,filename))
but "os.path.realpath(myfile)" instead of giving me the absolute path of "myfile" (I also tried "os.path.abspath(myfile)" but does the same thing basically), gives me the path from where the script is running; just like a os.chdir() with attached the myfile filename. basically os.path.realpath(myfile) = os.path.join(os.chdir(),myfile), whereas myfile is obviously in a any other random directory, so it shouldn't be.
When I try to move that file it says that it doesn't exist, and it's true, it is not in the path it goes to look.
How do I get the absolute path of the file I am walking on ("myfile")?
for root, subdirs, files in os.walk(this_path):
for my_file in files:
shutil.move(os.path.join(root, my_file), os.path.join(this_path, filename))