0

I am getting the error below when I run the script. It works fine on a workstation. I am pretty new with python. What could be the problem? I am trying to convert all csv files in that directory to ascii text files. Any help will be appreciated on identifying the error and fixing the code.

Script

import os
import csv


def csv_to_txt(csv_file):
  """Converts a CSV file to a TXT file.

  Args:
    csv_file: The path to the CSV file.

  Returns:
    The path to the created TXT file.
  """
  txt_file = csv_file[:-4] + ".txt"


  with open(csv_file, "r") as csvfile:
    reader = csv.reader(csvfile)
    with open(txt_file, "w") as txtfile:
      for row in reader:
        txtfile.write(", ".join(row) + "\n")

  return txt_file

def remove_old_txt_files(directory):
  """Removes all old CSV files from the specified directory.

  Args:
    directory: The directory to remove the CSV files from.
  """
  for file in os.listdir(directory):
    if file.endswith(".txt"):
      os.remove(os.path.join(directory, file))

def main():
  directory = "C:\Program Files\SplunkUniversalForwarder\etc\apps\TRENDMICRO_CSV_TO_TXT_SCRIPT\bin"

  # Remove all old TXT files.
  remove_old_txt_files(directory)

  # Convert all CSV files to TXT files.
  for file in os.listdir(directory):
    if file.endswith(".csv"):
      txt_file = csv_to_txt(os.path.join(directory, file))
      print("Converted {} to {}".format(file, txt_file))


if __name__ == "__main__":
  main()


Error

C:\Program Files\SplunkUniversalForwarder\etc\apps\TRENDMICRO_CSV_TO_TXT_SCRIPT\bin>python convert_csv_to_txt.py
Traceback (most recent call last):
  File "C:\Program Files\SplunkUniversalForwarder\etc\apps\TRENDMICRO_CSV_TO_TXT_SCRIPT\bin\convert_csv_to_txt.py", line 49, in <module>
    main()
  File "C:\Program Files\SplunkUniversalForwarder\etc\apps\TRENDMICRO_CSV_TO_TXT_SCRIPT\bin\convert_csv_to_txt.py", line 44, in main
    txt_file = csv_to_txt(os.path.join(directory, file))
  File "C:\Program Files\SplunkUniversalForwarder\etc\apps\TRENDMICRO_CSV_TO_TXT_SCRIPT\bin\convert_csv_to_txt.py", line 20, in csv_to_txt
    for row in reader:
_csv.Error: line contains NUL

So the code works very well on my workstation but prints the error above on a windows 2019 server

0 Answers0