1

Can anyone guide me on how to add a header to multiple csv files?

Optional: If anyone knows a method add add a header to pre-existing files in C# or can guide me to the relevant resources. That would be great.

import os
import os.path as path

## First create a function that will generate random files.
def create_random_csv_files(fault_classes, number_of_files_in_each_class):
    os.mkdir("./random_data/")  # Make a directory to save created files.
    for fault_class in fault_classes:
        for i in range(number_of_files_in_each_class):
            data = np.random.rand(1024,3)
            file_name = "./random_data/" + eval("fault_class") + "_" + "{0:03}".format(i+1) + ".csv" # This creates file_name
            np.savetxt(eval("file_name"), data, delimiter = ",", comments = "")
        print(str(eval("number_of_files_in_each_class")) + " " + eval("fault_class") + " files"  + " created.")
10
  • 2
    do not use eval ever! Commented Apr 17, 2020 at 20:03
  • 1
    @ShaR, check out stackoverflow.com/a/44428125/1886644 for the way to add a header to a csv file in C#. Commented Apr 17, 2020 at 20:07
  • 1
    @AntonPomieshchenko agreed it's definitely not good practice, I've never used it in my years of developing. However, that's not to say it doesn't have its place Commented Apr 17, 2020 at 20:10
  • 1
    BTW, eval("fault_class") seems like a difficult way to write fault_class and makes the code harder to read. Commented Apr 17, 2020 at 20:14
  • 1
    @ShaR eval, and its cousin exec, will execute arbitrary code without checking if it's safe code. Most of the time, whenever you are using those functions (especially a lot), you can refactor to a more efficient and pythonic implementation Commented Apr 17, 2020 at 20:15

1 Answer 1

0
import os
import os.path as path

## First create a function that will generate random files.
def create_random_csv_files(fault_classes, number_of_files_in_each_class):
    os.mkdir("./random_data/")  # Make a directory to save created files.
    for fault_class in fault_classes:
        for i in range(number_of_files_in_each_class):
            data = np.random.rand(1024,3)
            file_name = "./random_data/" + eval("fault_class") + "_" + "{0:03}".format(i+1) + ".csv" # This creates file_name
            np.savetxt("file_name", data, delimiter = ",", header = "V1,V2,V3", comments = "")
        print(str("number_of_files_in_each_class") + " " + "fault_class" + " files"  + " created.")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.