- 1 year ago
Counting number of files in subfolders and writing to text file
Comment
1 / 1
To count the number of files in subfolders and write the count to a text file using Python, you can use the os
module for directory operations. Here's an example code snippet:
pythonimport os
def count_files_in_subfolders(folder_path):
total_files = 0
for root, dirs, files in os.walk(folder_path):
total_files += len(files)
return total_files
def write_count_to_file(file_path, count):
with open(file_path, 'w') as file:
file.write(str(count))
# Specify the folder path to count files in
folder_path = '/path/to/folder'
# Count files in subfolders
file_count = count_files_in_subfolders(folder_path)
# Specify the file path to write the count
output_file_path = '/path/to/output.txt'
# Write the count to a text file
write_count_to_file(output_file_path, file_count)
In the above code:
- The
count_files_in_subfolders
function recursively walks through the directory tree usingos.walk
. It counts the number of files in each subfolder and returns the total count. - The
write_count_to_file
function writes the count to a text file using theopen
function in write mode ('w'). It converts the count to a string and writes it to the file. - You need to specify the
folder_path
variable with the path to the folder you want to count files in. - Specify the
output_file_path
variable with the path to the text file where you want to write the count.
After running the script, the total count of files in the subfolders will be written to the specified text file.