0

I have the following string

string = "First Name | Last Name | Age"

when I print it looks like this:

First Name | Last Name | Age

When I print to csv file

writer.writerow(datac[0])

looks like this:

F, i, r, s, t and so on...

How do I get to to print in single row? like this

Row1 

First Name | Last Name | Age
2
  • Have you tried writer.writerow([datac[0]])? Commented Nov 1, 2012 at 18:53
  • Are First Name, Last Name, and Age supposed to be separate columns? Commented Nov 1, 2012 at 20:03

2 Answers 2

2

writer.writerow() is expecting a sequence. Since strings are sequences of characters, it's being interpreted that way.

If your row contains only a single element, you could indicate that like this: writer.writerow([datac[0]]) or writer.writerow(datac[0:1])

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

2 Comments

This is correct, but possibly missing something. The very last line of his question shows that he may be expecting to write three (pipe delimeted?) columns, not one. (Incidentally, a csv file with one column doesn't need a separator.) If datac contains three items, what he really needs would be writer.writerow(datac).
If pipe-delimited is desired, pass the delimiter to the csv writer constructor: writer = csv.writer(a_file, delimiter='|')
1

writer.writerow() expects a sequence and when you give it a string it treats it as a sequence of charecters. Try doing this.

writer = csv.writer(csvfile, delimiter=' ')
string = "First Name | Last Name | Age"
writer.writerow(string.split('|'))

1 Comment

Unless you set your csv separator as '|', this will output using commas as delimiters, which seems to be different from what is desired.

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.