List of files, directories in Python
Here I present a short python program that prints the list of all files inside the current directory and subdirectories. It prints filename with relative path to the current directory.
You can also print the list of directories only (just print the dirs). Actually I needed this stuff to solve a problem from Google treasure hunt. Let me know if you want me to share the full source code of the solutions of Google treasure hunt. Also share your code, if you have any different idea!
Check the python documentation to learn more about processing Files and Directories.
import os
for root, dirs, files in os.walk('./'):
for name in files:
filename = os.path.join(root, name)
print filename
You can also print the list of directories only (just print the dirs). Actually I needed this stuff to solve a problem from Google treasure hunt. Let me know if you want me to share the full source code of the solutions of Google treasure hunt. Also share your code, if you have any different idea!
Check the python documentation to learn more about processing Files and Directories.
Comments
let me know if you want to see articles/tips on any topic in my blog. I shall try to write.
thanks a lot !
import os
f = open('myfile.txt', 'w')
for root, dirs, files in os.walk('./'):
for name in files:
filename = os.path.join(root, name)
s = filename + '\n'
f.write(s)
import os
f = open('myfile.txt', 'w')
for root, dirs, files in os.walk('./'):
for name in files:
filename = os.path.abspath(name)
s = filename + '\n'
f.write(s)
Throw in some list comprehensions for those nested for loops, and now our example looks like:
import os
f = open('myfile.txt', 'w')
# create a list of all files
# using list comprehensions
# should be all on one line
fnames = [os.path.join(root, name)
for (root,dirs,files) in os.walk('./')
for name in files]
s = "\n".join(fnames)
f.write(s)
You either do this (preferred):
with open('myfile.txt', 'w') as file:
#here you do the tree walking
or this longer version (they do exactly the same thing):
try:
file = open('myfile.txt', 'w')
#here do the tree walking
finally:
file.close()
Edit: Removed my first posting, because I forgot to use non-breaking spaces. Fixed it now.
The problem is that when I create new tarfile, it copies the old tarfile inside and also adds md5.txt file but the md5.txt file does not have any contains. However, the md5.txt file outside the new tarfile have the hash value.
Does anyone have some idea where I am going wrong or what I am missing. Thanks.
Akash...
I've been trying:
os.path.defpath'.:V:\\Kartdata'
and sys.path.append('V:\kartdata')
I want this program to search thru my V:\Kartdata directory. Any leads?
Thanks :)
I am very new to python . i need your great helps
requirement : I need to write python script for list file in a directory and then i need to print the contents of file . can you please help me out!
Thanks in Advance
karthik