Computer Science – 20.2 File Processing and Exception Handling | e-Consult
20.2 File Processing and Exception Handling (1 questions)
Model Answer 3
This solution uses the os and os.path modules to perform recursive directory traversal and file filtering.
import os
def findandlisttextfiles(directorypath, outputfilename):
text_files = []
for root, , files in os.walk(directorypath):
for file in files:
if file.endswith(".txt"):
text_files.append(os.path.join(root, file))
try:
with open(output_filename, 'w') as outfile:
for filepath in textfiles:
outfile.write(file_path + "\n")
except Exception as e:
print(f"Error writing to file '{output_filename}': {e}")
if name == "main":
directory_path = input("Enter the directory path: ")
outputfile = "alltext_files.txt"
findandlisttextfiles(directorypath, outputfile)
Explanation:
- The code uses
os.walk()to recursively traverse the directory specified by the user. - For each directory it visits, it iterates through the files in that directory.
- It checks if the file name ends with ".txt".
- If it does, it constructs the full path to the file using
os.path.join()and appends it to thetext_fileslist. - Finally, it writes each file path to the output file.
- Error handling is included for potential issues during file writing.