Rename file name in a directory using a for loop python

Aakash

I have a folder with the following contents in it:

  1. one folder named: 1_blocks
  2. list of 19 csv files by years: London_255_1999.csv, London_255_2000.csv, …, London_255_2017.csv
  3. one other csv file: London_xyz_combined_output_all_years.csv

The task is to rename only the 19 csv files using a for loop starting with London_255_1999.csv, …, London_255_2017.csv into London_245_1999.csv, …, London_245_2017.csv (i.e. replacing 255 to 245 in each given file name).

Here is my code. I don't want other files and folders to get renamed. Only the 19 files mentioned above.

path = r'A:\Engineering'

for f in os.listdir(path):
    if f.startswith("London_255") and not f.endswith('years.csv'): 
      f_name, f_ext = os.path.splitext(f)

      f_site, f_strings, f_year = f_name.split('_')

      f_strings='245'
      f_site=f_site
      f_year=f_year

      new_name = '{}_{}_{}{}'.format(f_site, f_strings, f_year, f_ext)

      os.rename(f,new_name)

Please suggest the easiest way to rename, if any. I am getting the following error:

f_site, f_strings, f_year = f_name.split('_')
ValueError: not enough values to unpack (expected 3, got 2)
Kevin Carr

I modified your code to use a regular expression to find the correct file format and ignore the final csv you mentioned. After it makes a correct match it uses the os and shutil built in libraries to rename the csv files into the new format you specificed.


import shutil, os, re

# create a regex that finds files
# within the specified directory
# that fits the format you wrote about
# above
# Essentially, this regex statement is saying look 
# for the following pattern [any amount of letters]_[3 digits]_[4 digits].csv
file_format_pattern = re.compile(r'[\w]+_[\d]{3}_[\d]{4}\.csv')

path = r'A:\Engineering'

for file in os.listdir(path):
# Loop over the files in the working directory.
    correct_file = file_format_pattern.search(file)
    # Skip files that aren't in the correct format
    if correct_file:
        f_name, f_ext = os.path.splitext(file)
        f_site, f_strings, f_year = f_name.split('_')
        # New Filename with 245 format instead of 255
        new_filename = f_site + "_245_" + f_year + f_ext

        # Get the full, absolute file paths.
        absWorkingDir = os.path.abspath(path)
        original_file = os.path.join(absWorkingDir, file)
        renamed_file = os.path.join(absWorkingDir, new_filename)

        # With shutil rename original filenames to new filename format
        shutil.move(original_file, renamed_file)  

You can learn a lot of cool ways to organize, re-write, read, and modify files automatically following this awesome automation book called "Automate the Boring Stuff" by Al Sweigart.

It's free online here and it teaches you how to utilize Python for automation in an easy to understand manner.

I basically followed the chapter here to help with your question.

For more understand of regex patterns check out chapter 7 of the book. I worked this on my workstation and it correctly renamed the csv files with the 255 format and ignored the final csv.

Please let me know if you have any questions and hope this helps. Cheers!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Python copy files to a new directory and rename if file name already exists

how can i rename using python any .xlsx file in a directory?

Rename all files in directory to line present in each file using python

how to get name of a file in directory using python

how to rename a file in a directory using current directory

Run the for loop for each file in directory using Python

Rename a file to parent directory's name in terminal

Rename Changing CSV file name in directory

Rename a file to part of the name of parent directory in linux

How to rename the user file name at the Users directory?

How to rename a specific word in a file name using python

How do I check the existing file with same name in the directory and use python to rename new files to save?

How to group file names in a directory using the file name extensions with python?

Compare lines in TXT file to excel file name in a directory using python

Is it possible to rename a file or directory using the inode?

No such file or directory while using os.rename

Is it possible to rename a file in C using directory streams?

Using `mv` to rename a file in nested directory

How to rename a file with a unique file name python

bash - loop through subdirectories, cat files and rename with directory name

C# rename a file to the same name as a file from a different directory

How to rename a file using Python

rename file when using DD name

Rename All Files in a Directory Using Python

file rename in bulk in powershell using foreach loop

Get the file name which contains the latest timestamp in a directory using python

Rename files in python depending on file name

For a directory, rename a file in a sub-directory with the sub-directory name+old filename into a new directory

Rename the pdf file inside sub-directories to the name of the sub directory