“Write a Python script that will export a list of all the files in a specified directory to a .txt file”
I was surprised of how clean and well detailed the code is. Of course it’s a simple script, but using ChatGPT to write no brainer code like this is great. It’s kinda weird that in of the attemps it wrote buggy code, I told it to rewrite and it corrected the code saying “I apologize for the mistake in the previous code. There is a naming conflict in the code where the name of the file being written to and the name of the loop variable are the same. This can cause the script to behave unexpectedly.”…
The script will print a .txt file that includes the current date in the file name and the total number of files and folders, as well as the total storage used in GB, at the end of the file:
import os
from datetime import datetime
# Prompt the user to enter the path to the directory
directory = input("Enter the path to the directory: ")
# Get the name of the directory
dir_name = os.path.basename(directory)
# Initialize variables to store the number of files, number of folders, and total storage used
num_files = 0
num_folders = 0
total_size = 0
# Walk through all the directories and subdirectories in the specified directory
for root, dirs, filenames in os.walk(directory):
# Increment the number of folders
num_folders += len(dirs)
# Increment the number of files
num_files += len(filenames)
# Add the size of all the files in the current directory to the total size
for filename in filenames:
total_size += os.path.getsize(os.path.join(root, filename))
# Convert the total size to GB
total_size_gb = total_size / (1024 ** 3)
# Get the current date and time
current_datetime = datetime.now()
# Construct the file name using the directory name and the current date and time
file_name = dir_name + '_' + current_datetime.strftime('%Y%m%d_%H%M%S') + '.txt'
# Open the file in write mode
with open(file_name, 'w') as outfile:
# Write the current date and time to the file
outfile.write('Date and time: ' + current_datetime.strftime('%Y-%m-%d %H:%M:%S') + '\n\n')
# Write the list of files to the file, with each file name on a new line
for root, dirs, filenames in os.walk(directory):
for filename in filenames:
outfile.write(os.path.join(root, filename) + '\n')
# Write the total number of files, folders, and storage used to the file
outfile.write('\nTotal number of files: ' + str(num_files) + '\n')
outfile.write('Total number of folders: ' + str(num_folders) + '\n')
outfile.write('Total storage used: {:.2f} GB\n'.format(total_size_gb))
print('File list exported to ' + file_name)
Ready to use and it works great for a fast directory check or small index.