Write string to file with different byte size?
<p>I am doing a Python scripting.</p>

<p>I have a string, the <code>len()</code> of the string is <code>1048576</code> and the <code>sys.getsizeof()</code> of the string is <code>1048597</code>.</p>

<p>However, when I write this string to a file, the byte size of the file is <code>1051027</code>. My code is below, anyone can tell me why the byte size of file is different with that of the string?</p>

<pre><code>print type(allInOne) # allInOne is my string
print len(allInOne)
print sys.getsizeof(allInOne)
newFile = open("./all_in_one7.raw", "w")
newFile.write(allInOne.encode('ascii'))
newFile.close()
</code></pre>

<hr>

<p>My string is <code>allInOne</code>, it is generated with many processes before, it was generated like this <code>allInOne = numpy.uint8(dataset.pixel_array).tostring()</code> , above this, <code>dataset.pixel_array</code> is of type <code>numpy.ndarray</code>. I don't know whether this info would be of any help.</p>

<p>Your <code>allInOne = numpy.uint8(dataset.pixel_array).tostring()</code> doesn't look like text. When writing anything but text to a file in Python, you need to <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files">open the file in binary mode</a> (<code>"wb"</code> instead of <code>"w"</code>) so that Python doesn't assume the <code>0x0A</code> bytes are <code>'\n'</code> line endings and attempt to convert them to the <code>'\r\n'</code> line endings that are more common on Microsoft Windows.</p>

<p>To see if this is your problem, <a href="https://stackoverflow.com/q/1155617/2738262">count that particular character</a>:</p>

<pre><code>print len(allInOne), "bytes"
print len(allInOne) + allInOne.count('\n'), "bytes with 0A counted twice"
</code></pre>

python file