Python IOError: [Errno 13] Permission denied in ubuntu?

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()
1

1 Answer

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like