0

so I have a question regarding a script i wrote including two functions. The idea is to anonymize all DICOM files (the dataformat for CT files) in a given folder, and move the anonymized files to new folder.

The issue is - the anonymizing function works by itself, the function which moves all the files from one folder to another as well. Unfortunately I'm not able to make both functions work in one loop.

Function for anonymizing DICOM files:

folder = r"C:.../test1"
target = r"C:.../test2"

def forceAnonymizeDICOMFile(inFile, outFile, dictionary = ''):
currentAnonymizationActions = initializeActions()

    del currentAnonymizationActions[(0x0010, 0x0020)]       
    del currentAnonymizationActions[(0x0010, 0x0040)]       
    if dictionary != '':
    currentAnonymizationActions.update(dictionary)

    dataset = pydicom.dcmread(inFile, force=True)
    
    dataset[(0x0010, 0x0010)].value = dataset[(0x0010,0x0020)].value 
 
    # Store modified image
    dataset.save_as(outFile)

Moving function:

def moving(folder, file, target):
    for file in files:
        shutil.move(os.path.join(folder, file), target)

Loop for connecting both:

subfolders = os.listdir(folder)

for idx, subfolder in enumerate(subfolders, 1):
    print(f"{idx}/{len(subfolders)} ({subfolder})")
    for file in os.listdir(folder+"/"+subfolder):
        filepath = folder+"/"+subfolder+"/"+file
        forceAnonymizeDICOMFile(filepath, filepath)
        moving(folder, file, target)

I feel like there is an error in my loop, since I get the error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:../test1'

I don't assume the error lies in both of the functions since they both work fien standalone.

Any help would be highly appreciated, thank you!

Anna Bleha
  • 63
  • 1
  • 1
  • 7

1 Answers1

1

I could actually solve it. The issue was that I didn't specify the folder structure in the target folder:

for file in os.listdir(folder+"/"+subfolder):
    filepath = folder+"/"+subfolder+"/"+file
    target_filepath = target+"/"+subfolder+"/"+file
    if os.path.isfile(target_filepath):
        continue
    print(f"Anonymizing file {filepath}")
    forceAnonymizeDICOMFile(filepath, target_filepath)

Now it is working properly. Thank you @Timus for your input!

Anna Bleha
  • 63
  • 1
  • 1
  • 7