1

I want to write string character to file, but i get error like this IOError: [Errno 13] Permission denied: '/python/add.txt'. how to solve this?

this is my code

q = open('/python/add.txt','r')
a = ['123', '234', '456']
lst = []
for line in q:
    for word in a:
        if word in line:
            line = line.replace(word + "\n",'')
    lst.append(line)
q.close()
z = open(r'/python/add.txt','w+')
for line in lst:
    z.write(line)
z.close()
2
  • 1
    You will need to chose a location for the add.txt file that is writable by the user who is running the code - usually that would be somewhere in the user's $HOME directory (like /home/username/Documents) Apr 27, 2020 at 21:09
  • Why do you feel a need to store data in a directory under the Root-directory of the file system? There is typically very little reason to do so... When opening file in Python, it is way better to use the with statement. Python will take care than that the file is closed automatically when no longer needed.
    – noisefloor
    Aug 5, 2023 at 8:23

1 Answer 1

1

You have 3 choices:

  • Run your script as root user. I.e.:

    sudo ./path/to/your/script.py or sudo python3 path/to/your/script.py

  • Grant read, write & execute permissions to /python and read & write permissions to /python/add.txt for your user/group. There are a few ways to reach that ends, e.g.:

    sudo chown -R my_user:my_user /python && sudo chmod u+rw /python/add.txt

  • Put add.txt somewhere else (as per @steeldriver's comment) such as within your users $HOME.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .