Remove folders but the csv files

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To remove folders but keep the CSV files within them, you can use the following approach in a Python script:

python
import os

# Define the root directory
root_dir = 'path/to/root/directory'

# Iterate over the directories and files within the root directory
for dirpath, dirnames, filenames in os.walk(root_dir):
# Remove the subdirectories
for dirname in dirnames:
dir_to_remove = os.path.join(dirpath, dirname)
os.rmdir(dir_to_remove)

# Keep the CSV files
for filename in filenames:
if filename.endswith('.csv'):
# Optionally, you can move or copy the CSV files to a different location
csv_file = os.path.join(dirpath, filename)
# Perform desired operations with the CSV file

# Break the loop after processing the root directory
break

Make sure to replace 'path/to/root/directory' with the actual path to your root directory. The script uses the os.walk function to traverse the directory tree and iterates over the directories and files within it. It removes the subdirectories using os.rmdir and keeps the CSV files based on their file extension (.csv in this example). You can perform any desired operations on the CSV files within the corresponding loop.

Please exercise caution when using code to remove directories, as it can permanently delete data. Ensure that you have a backup or take necessary precautions before running such code.