1

I'm trying to write a csv file from json data. During that, i want to write '001023472' but its writing as '1023472'. I have searched a lot. But dint find an answer.

The value is of type string before writing. The problem is during writing it into the file.

Thanks in advance.

5
  • change the type to str like str(001023472) Commented Oct 9, 2014 at 7:12
  • You can use formatting Commented Oct 9, 2014 at 7:13
  • Look at the chapter on Strings in the Python manual. Much of it is dedicated to formatting output. docs.python.org/3.5/library/string.html Commented Oct 9, 2014 at 7:16
  • 1
    @AvinashGarg that is a SyntaxError in Python 3 (leading 0s are prohibited in numeric literals), and in Python 2 it will convert the number to octal (would be a SyntaxError if there were an 8 or 9). Commented Oct 9, 2014 at 7:22
  • @AvinashGarg plus it doesn't seem like the OP actually has a literal but something from a JSON. Commented Oct 9, 2014 at 7:26

2 Answers 2

1

Convert the number to string with formatting operator; in your case: "%09d" % number.

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

Comments

1

Use the format builtin or format string method.

>>> format(1023472, '09')
'001023472'
>>> '{:09}'.format(1023472)
'001023472'

If your "number" is actually a string, you can also just left-pad it with '0''s:

>>> format('1023472', '>09')
'001023472'

The Python docs generally eschew % formatting, saying it may go away in the future and is also more finnicky; for new code there is no real reason to use it, especially in 2.7+.

4 Comments

still i get the value as '1023472' in my csv file. i want '001023472'
Is it a string from your CSV? You could cast it to int then use the format methods, or just pad the string with 0's.
i'm writing in a csv file from json data. one of my json value is '001023472' which i want to write into one of columns in csv file. But there seems to be a problem while writing. the value is of type string but when i write it to csv it is changed as int.
What are you writing your CSV with? I don't think the standard library csv package converts strings to ints. I'm still a bit confused as to the type() of your "json value".

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.