This is currently my Python Script to convert CSV-Files to XML-Files

def on_created(self, event):
    if event.is_directory or not event.src_path.endswith(".csv"):
        return

    csv_file_path = event.src_path
    print(f"CSV-Dateipfad: {csv_file_path}")
    self.process_csv_file(csv_file_path)
    logging.info(self.process_csv_file(csv_file_path))

def process_csv_file(self, csv_file_path):
    # Erzeuge einen XML-Dateinamen basierend auf dem CSV-Dateinamen
    csv_filename = os.path.basename(csv_file_path)
    xml_filename = os.path.splitext(csv_filename)[0] + ".xml"
    # Erstelle den vollständigen Pfad für die XML-Datei
    xml_file_path = os.path.join(self.output_folder, xml_filename)

    # Konvertiere CSV in XML
    self.convert_csv_to_xml(csv_file_path, xml_file_path)
    print(self.convert_csv_to_xml(csv_file_path, xml_file_path))
    logging.info(self.convert_csv_to_xml(csv_file_path, xml_file_path))

    logging.info(f"CSV-Datei konvertiert: {csv_file_path} -> {xml_file_path}")

def convert_csv_to_xml(self, csv_file_path, xml_file_path):
    with open(csv_file_path, 'r', newline="") as file:
        csv_reader = csv.DictReader(file, delimiter=";")

        namespaces = {
            'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance",
            'xmlns:xsd': "http://www.w3.org/2001/XMLSchema",
            'xmlns': "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
        }

        # Create the SEPA Pain.001 XML structure
        document = ET.Element("Document", attrib=namespaces)
        cct_init = ET.SubElement(document, "CstmrCdtTrfInitn")

        # Group Header
        grp_header = ET.SubElement(cct_init, "GrpHdr")
        msg_id = ET.SubElement(grp_header, "MsgId")
        msg_id.text = "SEPA_PAYMENT-04254"  # Set a custom message ID

        cre_dt_tm = ET.SubElement(grp_header, "CreDtTm")
        cre_dt_tm.text = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

        nb_of_txs = ET.SubElement(grp_header, "NbOfTxs")
        ctrl_sum = ET.SubElement(grp_header, "CtrlSum")

        initg_pty = ET.SubElement(grp_header, "InitgPty")
        ET.SubElement(initg_pty, "Nm").text = "YOUR_INITIATOR_NAME"

        # For Loop to put the Payment Information
        for row in csv_reader:
            # Debitor Information
            nb_of_txs.text = str(int(nb_of_txs.text or "0") + 1)
            ctrl_sum.text = row["Bruttobetrag (gesamt) [Zahlungsdaten]"].replace(',', '.')

            # Payment Information
            PmtInf = ET.SubElement(cct_init, "PmtInf")
            ET.SubElement(PmtInf, "PmtInfId").text = "YOUR_PAYMENT_INFO_ID"
            ET.SubElement(PmtInf, "PmtMtd").text = "TRF"
            ET.SubElement(PmtInf, "BtchBookg").text = "false"

            reqd_colltn_dt = ET.SubElement(PmtInf, "ReqdExctnDt")
            reqd_colltn_dt.text = datetime.strptime(
            row["Zahlungsziel [Zahlungsdaten]"], "%d.%m.%Y")
            .strftime("%Y-%m-%d")

            Dbtr = ET.SubElement(PmtInf, "Dbtr")
            ET.SubElement(Dbtr, "Nm").text = " "

            DbtrAcct = ET.SubElement(PmtInf, "DbtrAcct")
            ET.SubElement(DbtrAcct, "Id").text = " "

            DbtrAgt = ET.SubElement(PmtInf, "DbtrAgt")
            ET.SubElement(DbtrAgt, "FinInstnId").text = " "

            CdtTrfTxInf = ET.SubElement(PmtInf, "CdtTrfTxInf")
            PmtId = ET.SubElement(CdtTrfTxInf, "PmtId")
            ET.SubElement(PmtId, "EndToEndId").text = f"TRANSACTION-{csv_reader.line_num - 1}"

            Amt = ET.SubElement(CdtTrfTxInf, "Amt")
            ET.SubElement(Amt, "InstdAmt", Ccy="EUR").text = row[
                "Bruttobetrag (gesamt) [Zahlungsdaten]"].replace(',', '.')

            CdtrAgt = ET.SubElement(CdtTrfTxInf, "CdtrAgt")
            BIC = ET.SubElement(CdtrAgt, "FinInstnId")
            ET.SubElement(BIC, "BIC").text = row["BIC [Zahlungsdaten]"]

            Cdtr = ET.SubElement(CdtTrfTxInf, "Cdtr")
            ET.SubElement(Cdtr, "Nm").text = row["Zahlungsempfaenger [Zahlungsdaten]"]

            CdtrAcct = ET.SubElement(CdtTrfTxInf, "CdtrAcct")
            IBAN = ET.SubElement(CdtrAcct, "Id")
            ET.SubElement(IBAN, "IBAN").text = row["IBAN [Zahlungsdaten]"]

            RmtInf = ET.SubElement(CdtTrfTxInf, "RmtInf")
            ET.SubElement(RmtInf, "Ustrd").text = row["Verwendungszweck [Zahlungsdaten]"]

        file.close()

        xml_tree = ET.ElementTree(document)
        xml_tree.write(xml_file_path, encoding="utf-8", xml_declaration=True)


def start_csv_handler(output_folder):
    event_handler = CSVHandler(output_folder)
    observer = Observer()
    observer.schedule(event_handler, path=output_folder, recursive=False)
    observer.start()

    logging.info(f"Überwache den Ordner: {output_folder}")
    try:
        while True:
            root.update()
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


if __name__ == "__main__":
    root = tk.Tk()
    root.withdraw()

    # Wähle den Ausgabeordner für die XML-Dateien
    output_folder = filedialog.askdirectory()
    if not output_folder:
        logging.info("Kein Ausgabeordner ausgewählt.")
        exit()

    logging.basicConfig(filename="logfile.log", level=logging.INFO, format="%(asctime)s - %(levelname)s 
    - %(message)s")
    logging.info(f"Ausgebeordner ausgewählt: {output_folder}")
    thread = threading.Thread(target=start_csv_handler, args=(output_folder,))
    thread.start()

    root.mainloop()

`

In this script I am trying to monitor a network folder. In this Folder there are CSV-Files. The CSV-Files should convert it into an XML-File. The Problem is if i run this Script on a Windows Device i get an PermissionError: [Errno 13] Permission denied: But if i run this Script on a MacOs Device it works perfectly. I don't know why it isn't working on a Windows Device. I already tried to run cmd as a administrator and i still get this error. Also i checked the settings of the folder and it has reading and write permission.

Can someone help?

This is the complete Error Message:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Users\Administrator.VERTRIEB-PC21\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\watchdog\observers\api.py", line 204, in run
    self.dispatch_events(self.event_queue)
  File "C:\Users\Administrator.VERTRIEB-PC21\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\watchdog\observers\api.py", line 380, in dispatch_events
    handler.dispatch(event)
  File "C:\Users\Administrator.VERTRIEB-PC21\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\watchdog\events.py", line 276, in dispatch
    {
  File "C:\Users\Administrator.VERTRIEB-PC21\Desktop\NeuerOrdner\Hdd.py", line 26, in on_created
    self.process_csv_file(csv_file_path)
  File "C:\Users\Administrator.VERTRIEB-PC21\Desktop\NeuerOrdner\Hdd.py", line 37, in process_csv_file
    self.convert_csv_to_xml(csv_file_path, xml_file_path)
  File "C:\Users\Administrator.VERTRIEB-PC21\Desktop\NeuerOrdner\Hdd.py", line 54, in convert_csv_to_xml
    with open(csv_file_path, 'r', newline="") as file:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: 'S:/SepaPain/ExportCSV\\DocuWare_Dokumentenpool_2023.06.20.csv'
0

There are 0 best solutions below