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.

1
  • 1
    can you please give the full code and output with screeshot or table structure Commented Jun 24, 2020 at 6:55

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

but i need to give coulmn name to each coulmn
Just write it once before the loop, see the link I provided.
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]]

Comments

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)

Comments

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
`

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.