Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Move files to root directory in Ubuntu

I have to move all files from a particular directory to a root directory by using Python script. I failed with the following code with [Errno 13] Permission denied error.

import shutil
import os

source = '../json' 
dest = '/var/www/json'
files = os.listdir(source)

for f in files:
    shutil.move(source+"/"+f, dest)

Is it possible to add sudo with this code or is there any other method to move files to root folder? I am working in Ubuntu16.04

like image 400
Muhzin Avatar asked Aug 05 '26 20:08

Muhzin


2 Answers

I can think of three possible solutions to this:

  1. Running python as sudo: sudo python script.py. Probably not the nicest way as there are possible security concerns.
  2. Change the permissions of the folder so the user running the python script has access to copy/edit files in those folders.
  3. Call cp/mv as a subprocess from python as root. Basically the same as the first option. Can either be done by getting the user to type in root's password which I guess isn't great for you. Or you can use something like polkit to avoid using a password.

I would suggest the 2nd option is best and easiest in the long run.

like image 101
Tom Dee Avatar answered Aug 08 '26 10:08

Tom Dee


you could add your user to the folder permissions and give the user write access to that folder. use chown or chmod to adjust permissions on the destination folder

like image 29
shawn bright Avatar answered Aug 08 '26 08:08

shawn bright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!