win32fileDemo.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # This is a "demo" of win32file - it used to be more a test case than a
  2. # demo, so has been moved to the test directory.
  3. # Please contribute your favourite simple little demo.
  4. import win32file, win32api, win32con
  5. import os
  6. # A very simple demo - note that this does no more than you can do with
  7. # builtin Python file objects, so for something as simple as this, you
  8. # generally *should* use builtin Python objects. Only use win32file etc
  9. # when you need win32 specific features not available in Python.
  10. def SimpleFileDemo():
  11. testName = os.path.join( win32api.GetTempPath(), "win32file_demo_test_file")
  12. if os.path.exists(testName): os.unlink(testName)
  13. # Open the file for writing.
  14. handle = win32file.CreateFile(testName,
  15. win32file.GENERIC_WRITE,
  16. 0,
  17. None,
  18. win32con.CREATE_NEW,
  19. 0,
  20. None)
  21. test_data = "Hello\0there".encode("ascii")
  22. win32file.WriteFile(handle, test_data)
  23. handle.Close()
  24. # Open it for reading.
  25. handle = win32file.CreateFile(testName, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
  26. rc, data = win32file.ReadFile(handle, 1024)
  27. handle.Close()
  28. if data == test_data:
  29. print("Successfully wrote and read a file")
  30. else:
  31. raise Exception("Got different data back???")
  32. os.unlink(testName)
  33. if __name__=='__main__':
  34. SimpleFileDemo()