How to move files on Drive folder from Google Collab?

Issue

I’m using this code to read paths inside a txt file, the code changes the extension of the paths from jpg to json.

%cd /content
eliminados = 0
with open('vuelo1.txt') as b:
  for o in b:
    o = o.replace("jpg", "json")
    print('path:',o)
    eliminados = eliminados + 1
    !mv $o /content/drive/MyDrive/Banano/etiquetas_eval/Datasets_originales_inferidos/etiquetas/malas/$etiquetas/
print(eliminados)

Then I need to move the json files to another folder for which I use the following line:

!mv $o /content/drive/MyDrive/Banano/etiquetas_eval/Datasets_originales_inferidos/etiquetas/malas/$etiquetas/

where $o is the path of the json file inside the txt file and the next path is the destination folder

However I get this error:

mv: missing destination file operand after '/content/drive/MyDrive/Banano/etiquetas_eval/Datasets_originales_inferidos/ric/vuelo1/DJI_0338_2-1.json'
Try 'mv --help' for more information.
/bin/bash: line 1: /content/drive/MyDrive/Banano/etiquetas_eval/Datasets_originales_inferidos/etiquetas/malas/vuelo1/: Is a directory
path: /content/drive/MyDrive/Banano/etiquetas_eval/Datasets_originales_inferidos/ric/vuelo1/DJI_0332_1-2.json

Any idea what I’m doing wrong?

Solution

There’s a newline at the end of $o, so your !mv $o /content/drive/.. is broken into 2 lines / commands:

mv /content/drive/.../DJI_0338_2-1.json
/content/drive/.../malas/vuelo1/

That’s why you see 2 separate error messages.

Try replacing o = o.replace("jpg", "json") with o = o.rstrip().replace("jpg", "json")
to strip newlines.

Debugging tip: using something like print(f'path: "{o}"') makes it far easier to spot such issues; and if you are not quite sure what exactly gets sent to Bash or how vars are evaluated, test your commands with echo first:
!echo mv $o /content/drive/.../malas/$etiquetas/

Answered By – margusl

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published