Directory Tree:
% tree .
.
├── the_king
│ └── text.txt
├── the_knight
│ └── text.txt
├── the_peasant
│ └── text.txt
└── wart.py
3 directories, 4 files
Directories and contents up to:
% find . -name 'text.txt' -print -exec cat {} \;
./the_king/text.txt
has a wart
was dressed up like a witch
has a false nose
./the_knight/text.txt
has a wart
was dressed up like a witch
has a false nose
./the_peasant/text.txt
has a wart
was dressed up like a witch
has a false nose
Code (wart.py):
import os
text_file = 'text.txt'
cwd = os.path.curdir
for root, dirs, files in os.walk(cwd):
if text_file in files:
print 'Found %s!' % root
filepath = os.path.join(root, text_file)
root_base = os.path.basename(root)
output = ''
with open(filepath, 'r') as reader:
for line in reader:
new_line = "%s %s" % (root_base, line)
print new_line,
output += new_line
with open(filepath, 'w') as writer:
writer.write(output)
print
What outputs:
Found ./the_king!
the_king has a wart
the_king was dressed up like a witch
the_king has a false nose
Found ./the_knight!
the_knight has a wart
the_knight was dressed up like a witch
the_knight has a false nose
Found ./the_peasant!
the_peasant has a wart
the_peasant was dressed up like a witch
the_peasant has a false nose
Directories and contents after:
% find . -name 'text.txt' -print -exec cat {} \;
./the_king/text.txt
the_king has a wart
the_king was dressed up like a witch
the_king has a false nose
./the_knight/text.txt
the_knight has a wart
the_knight was dressed up like a witch
the_knight has a false nose
./the_peasant/text.txt
the_peasant has a wart
the_peasant was dressed up like a witch
the_peasant has a false nose
It was fun! Thanks for the call!
source
share