title: Is it possible to get writing access to raw devices using python with windows?
body: <p>This is sort of a follow-up to <a href="https://stackoverflow.com/questions/6522644/how-to-open-disks-in-windows-and-read-data-at-low-level">this question</a>. I want to know if you can access raw devices (i.e. <code>\\.\PhysicalDriveN</code>) in writing mode and if this should be the case, how.</p>
  
  <p>Using Linux, write access can simply be achieved by using e.g. <code>open("/dev/sdd", "w+")</code> (provided that the script is running with root permissions). I assume that Mac OS behaves similar (with <code>/dev/diskN</code> as input file).</p>
  
  <p>When trying the same command under Windows (with the corresponding path), it fails with the following error:</p>
  
  <pre><code>IOError: [Errno 22] invalid mode ('w+') or filename: '\\\\.\\PhysicalDrive3'
  </code></pre>
  
  <p>However, when trying to <strong>read</strong> from the PhysicalDrive, it <em>does work</em> (even the correct data is read). The shell is running with administrator permissions under Windows 7. </p>
  
  <p>Is there any other way to accomplish this task using python while still keeping the script as platform-independent as possible?</p>
  
  <h2>Edit:</h2>
  
  <p>I looked a bit further into what methods python provides for file handling and stumbled across <a href="http://docs.python.org/library/os.html#os.open" rel="noreferrer">os.open</a>. Opening the PhysicalDrive using <code>os.open(drive_string, os.O_WRONLY|os.O_BINARY)</code> returns no error. So far, so good. Now I have either the choice to write directly to this file-descriptor using <a href="http://docs.python.org/library/os.html#os.write" rel="noreferrer">os.write</a>, or use <a href="http://docs.python.org/library/os.html#os.fdopen" rel="noreferrer">os.fdopen</a> to get a file-object and write to it in the regular way.
  Sadly, none of these possibilities works. In the first case (<code>os.write()</code>), I get this:</p>
  
  <pre><code>&gt;&gt;&gt; os.write(os.open("\\\\.\\PhysicalDrive3", os.O_WRONLY|os.O_BINARY), "test")
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  OSError: [Errno 22] Invalid argument
  </code></pre>
  
  <p>In the second case, I <strong>can</strong> create a file object with write permissions, but the writing itself fails (well, after enforcing its execution using <code>.flush()</code>):</p>
  
  <pre><code>&gt;&gt;&gt; g = os.fdopen(os.open("\\\\.\\PhysicalDrive3", os.O_WRONLY|os.O_BINARY), "wb")
  &gt;&gt;&gt; g.write("test")
  &gt;&gt;&gt; g.flush()
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  IOError: [Errno 22] Invalid argument
  </code></pre>