0

I am pulling data from a Rally server, and would like to write it to a CSV file and create snapshots. I am creating the file with:

orig_stdout = sys.stdout
timestr = time.strftime("%m-%d-%Y")
f = open(timestr+'FileName.csv', 'w')
sys.stdout = f

#all of the setup and functions

sys.stdout = orig_stdout
f.close()

The output I am writing to file comes from:

for item in response:
    print("%s, %s, %s, %s" % (item.Attribute1, item.Attribute2, item.Attribute3, item.Attribute4))

The problem is that the strings will occasionally have a comma in it already. This is true for every usual character. I do not wish to replace the commas in said strings.

Is there a special character I can use that an Excel CSV file would recognize and be able to split into columns properly, or can I somehow tell the file to delimit using a multiple characters such as ",,"

3
  • Have you looked at the csv module? Commented Sep 28, 2017 at 17:53
  • Oh I feel stupid now; I'm new to python (I mainly work with SQL or tools like Tableau). My initial search for an answer didn't turn up the csv module, but I could have guessed that one existed. Thank you for the help. Commented Sep 28, 2017 at 17:58
  • One hint if you're new to python: Don't redirect sys.stdout to a file just to use print. Instead use an approach like with open('file.csv', 'w') as out: out.write('text') Commented Sep 28, 2017 at 18:51

1 Answer 1

1

Python has a built-in csv modules that can handle various formats (such as excel) and can handle special options (such as escaping) automatically for you.

The Writer object from the CSV module sounds like what you're looking for.

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.