pythonshutil

Copying a file into multiple folders using Python


I have a file Test.py. I am pasting this file into 2 different folders as shown below but I also want to change File=1 based on the folder it was pasted. For example, it is pasting Test.py into folders 1,2 with the same File=1. Instead, I want to paste Test.py into folders 1,2 with File=1 and File=2 respectively.

The content of Test.py is

File=1

The code I am using to paste is

import shutil
N=[1, 2]

src_path = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\Test.py"
for i in N:
    dst_path = rf"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\{i}"
    File={i}
    shutil.copy(src_path, dst_path)
    print('Copied')

Solution

  • Your instruction File={i} has no effect on the content of the file you copy. To change this variable in the file, you must directly edit the text, the content, of the file.

    To do so, you'll need a regex to detect the text you want to change. The expression that finds the text 'File=' followed by any number of digits is r"File=\d*".

    So instead of copying, what you need to do is:

    Here is an example (you don't need shutil here):

    import re
    
    N=[1, 2]
    
    pattern_to_replace = re.compile(r"File=\d*")  
    
    src_path = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\Test.py"
    
    for i in N:
    
        # Get content of src file
        with open(src_path, 'r') as src:
            content = src.read()
    
        # Modify this content
        updated_content = re.sub(pattern_to_replace, f"File={i}", content)
    
        # Create the new file
        dst_path = rf"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\{i}"
       with open(dst_path, 'w') as dst:
           dst.write(updated_content)
    
        print('Copied')