0

I m using the below python code to write data to a CSV file with column name.

def get_filename_datetime():
    # Use current date to get a text file name.
    return "Report-" + str(datetime.date.today())
# Get full path for writing.
filename = get_filename_datetime()
Data = [["FirstName", "LastName","Failed_User_Id"],
          [firstname, lastname, faileduserid]]
Reportfilename = os.path.join(reportspath, filename)
myfile = open(Reportfilename + '-Results.csv', "a+")
with myfile:
    writer = csv.writer(myfile)
    writer.writerows(Data)

I'm getting output in a file as:

actual output

My expected output is:

I'm getting output in a file as:

expected output

But I'm getting column name printed for each and every row.

m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
sri
  • 11
  • 2
  • 5

4 Answers4

0

That is because they are in the list Data:

Data = [["FirstName", "LastName","Failed_User_Id"],
                      [firstname, lastname, faileduserid]]

simply remove them:

Data = [[firstname, lastname, faileduserid]]

Examples of how to write header here.

schoon
  • 2,858
  • 3
  • 46
  • 78
0

I guess you're using method get_filename_datetime in loop, so you're keep appending this to the CSV file:

Data = [["FirstName", "LastName","Failed_User_Id"],
                      [firstname, lastname, faileduserid]]

Solution is moving column name outside of loop, append only row data:

 Data = [[firstname, lastname, faileduserid]]
mtdot
  • 312
  • 2
  • 10
0

You are getting the headers repeated because every time you are adding a row you also adding the headers again You need to separate the first row in Data and write it once

def get_filename_datetime():
    # Use current date to get a text file name.
    return "Report-" + str(datetime.date.today())
# Get full path for writing.
filename = get_filename_datetime()
headers = ["FirstName", "LastName","Failed_User_Id"]     
Data = [firstname, lastname, faileduserid]
Reportfilename = os.path.join(reportspath, filename)
myfile = open(Reportfilename + '-Results.csv', "a+")
with myfile:
   writer = csv.writer(myfile)
   if(os.stat(myfile).st_size == 0):
      writer.writerows(header) 
    writer.writerows(Data)
Mostafa Labib
  • 789
  • 6
  • 17
0

Both answers by @mtdot and @schoon are correct

If you want to use pandas

you can use this

`
columns = ['FirstName', 'LastName', 'Failed_User_Id']
header = True
for dataset in datasets:
    df = pd.DataFrame(dataset)
    df = df[columns]
    mode = 'a+'
    df.to_csv('./new.csv', encoding='utf-8', mode=mode, header=header, index=False)
    header = False
`