i want a list of csv files that i want to rename them give me the proper python code
- User
i want a list of csv files that i want to rename them give me the proper python code
- Assistant
To rename CSV files in a directory using Python, you can use the
osmodule, which provides functions for interacting with the operating system. Below is a sample Python script that lists all the CSV files in a specified directory and renames them according to your naming scheme.Note: Before running the script, ensure you have a backup of your files or are working in a directory where any mistakes can be safely made, to avoid losing data.
import os # Specify the directory containing the CSV files directory = '/path/to/your/csv/files' # Specify your new file name base new_file_name_base = "new_name_" # Use os.listdir to list all files and os.rename to rename them for filename in os.listdir(directory): if filename.endswith(".csv"): old_file_path = os.path.join(directory, filename) # Generating new file name # If you have a specific naming scheme, modify this part new_filename = new_file_name_base + filename new_file_path = os.path.join(directory, new_filename) # Renaming the file os.rename(old_file_path, new_file_path) print(f"Renamed '{filename}' to '{new_filename}'") print("Renaming complete.")