-1

new to Python.

Even when doing a simple write to file I get an error

simple code

text = "Sample text."
saveFile = open("file.txt", "w")
saveFile.write(text)
saveFile.close()

error OSError: [Errno 9] Bad file descriptor

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Tony\Documents\PythonCourse\App1\tester.py", line 4, in <module>
saveFile.close()
OSError: [Errno 9] Bad file descriptor

doing this without a close does not give an error but does not write to the file.

I'm lost as to what to try next

  • 1
    This works just fine, so you're going to have to get a lot more detailed: which OS? (Obviously windows, but which one?) Which version of Python? What execution environment? – Mike 'Pomax' Kamermans Jul 13 '23 at 02:48
  • I think the most likely cause is that the file was never actually opened. Try leaving out the `write` and see if you get the same error. – Mark Ransom Jul 13 '23 at 02:52
  • Sorry. Windows 11. IDE is pycharm – Tony Wilson Jul 13 '23 at 03:29
  • If I leave out the write, I do not get an error – Tony Wilson Jul 13 '23 at 03:29
  • python version is 3.11 – Tony Wilson Jul 13 '23 at 03:30
  • Does this answer your question? [What can lead to "IOError: \[Errno 9\] Bad file descriptor" during os.system()?](https://stackoverflow.com/questions/7686275/what-can-lead-to-ioerror-errno-9-bad-file-descriptor-during-os-system) – Osadhi Virochana Jul 13 '23 at 03:32
  • Also works for me on Windows 11. Try in a python console, try different folder, make sure you have free storage/are allowed to write, make sure the file is NOT currently open/edited with another program. Try to modify to another filename, if this works the first time. Its rather an OS file locked by something else problem. – Amegon Jul 14 '23 at 15:00

1 Answers1

-2

Hope this will work as if the "saveFile.write(text)" throws any kind of error, so it won't allow us to close our file (saveFile.close()) it could be resolved using the exception handling.

text = "Sample text."
saveFile = open("file.txt", "w")
try:
    saveFile.write(text)
finally:
    saveFile.close()
  • C:\Users\Tony\AppData\Local\Programs\Python\Python311\python.exe C:\Users\Tony\Documents\PythonCourse\App1\tester.py OSError: [Errno 9] Bad file descriptor During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Tony\Documents\PythonCourse\App1\tester.py", line 6, in saveFile.close() OSError: [Errno 9] Bad file descriptor Process finished with exit code 1 – Tony Wilson Jul 13 '23 at 03:28