-1
import os

# Open the file in write-only mode
g = os.open("d:\Coding\Python\OS module practise.txt", os.O_WRONLY)
os.write(g, b"Hi")

I ran this code and I am getting the following error

Traceback (most recent call last): File "d:\Coding\Python\Practice files\Practice\day 12\practice4.py", line 7, in os.write(g, b"HI") OSError: [Errno 9] Bad file descriptor

I don't understand what is the problem?

I tried adding "Hi" to the txt file but it threw an error.

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46

1 Answers1

0

\ is a special character in strings. For example, \n means newline, \t means TAB. If you want to include an actual \ character in a string, you will need to "escape" the \ with an extra \. Try: "d:\\Coding\\Python\\OS module practise.txt"

I will also note that there is an easier way to append to a file!

filename = "d:\\Coding\\Python\\OS module practise.txt"
with open(filename, 'a+') as file:
    current_text = file.read()
    new_text = current_text + "Hi!"
    file.write(new_text)
Matt
  • 973
  • 8
  • 10
  • 1
    Raw strings or using `/` are easier. – Barmar Aug 04 '23 at 22:01
  • sub·jec·tive adjective: subjective 1. based on or influenced by personal feelings, tastes, or opinions. "his views are highly subjective" – Matt Aug 04 '23 at 22:06
  • 1
    Less error-prone, IMHO. The more things you have to add, the more likely you are to miss one. – Barmar Aug 04 '23 at 22:08
  • And it looks just like a pathname the way you use it in other contexts. Being different is confusing. – Barmar Aug 04 '23 at 22:08
  • OP forgot to close their file as well. Using a `with` context manager simplifies things. – Matt Aug 04 '23 at 22:09
  • I assumed the OP is deliberately playing with the `os` functions, so not interested in the python built-in way. `os.open()` doesn't implement a context manager, since it just returns an int. – Barmar Aug 04 '23 at 22:31