0

I am currently working with several XML files that require the text of the element mods:namePart changed. I have created a script that should loop through all the XML files I have specified in a particular directory and make the intended changes. However, when I run the script the changes are not reflected in the new files. It executes as expected, and I even get the "namepart changed" output in my console, but the text I want to replace remains the same. PLEASE HELP!! I am extremely new to coding so any tips/comments are welcome. Here is the code I'm using:

list_of_files = glob.glob('/Users/#####/Documents/test_xml_files/*.xml')

for file in list_of_files: xmlObject = ET.parse(file)

root = xmlObject.getroot()

namespaces = {'mods':'http://www.loc.gov/mods/v3'}

for namePart in root.iterfind('mods:name/mods:namePart', namespaces):
    if namePart.text == 'Tsukioka, Kōgyo, 1869-1927':
        new_namePart = namePart.text.replace('Tsukioka, Kōgyo, 1869-1927', 'Tsukioka Kōgyo, 1869-1927', 1)
        namePart.text == new_namePart
        print('namepart changed')
    else:
        continue

nf = open(os.path.join('/Users/####/Documents/updated_test_directory', os.path.basename(file)), 'wb')
xmlString = ET.tostring(root, encoding="utf-8", method="xml", xml_declaration=None)
nf.write(xmlString)
nf.close()
BlackList96
  • 176
  • 2
  • 9
khes
  • 13
  • 4
  • Maybe it's this? `namePart.text == new_namePart` That's an equality comparison returning true or false, which is ignored, but it's probably supposed to be `namePart.text = new_namePart`. I'm actually not that strong on Python but I noticed that. – user2740650 Aug 16 '20 at 14:46
  • Thanks! A typo on my end. I fixed it, but alas, no change, ugh. – khes Aug 16 '20 at 14:54
  • Yeah I wasn't sure it would help. The read operation is probably creating temporary variables, and you're updating a temporary variable, but that doesn't mean it's going to get written back out. I'm not sure what "several" means, but if it's just a handful you could group-replace with a text editor. If you need to write a program, check out this answer: https://stackoverflow.com/questions/1591579/how-to-update-modify-an-xml-file-in-python as it might give some guidance. – user2740650 Aug 16 '20 at 15:00

0 Answers0