9

The program takes an optional command line argument (which is meant to be a directory path)

I am using python pathlib and shutil to move files. Here's the code:

from pathlib import Path

path = Path(sys.argv[1])

shutil.move(path / file, path / e.upper())

Where e is just a string representing certain file extension;

Input:

 python3 app.py /home/user/Desktop

This code generates an error:

'PosixPath' object has no attribute 'rstrip'

The / operator works fine if I don't specify the second argument in the command line (and use Path.cwd() as the path instead)

  • 1
    Please show the full stack trace, what you have there is not enough – Hai Vu Apr 20 '20 at 16:35
  • 1
    The code you posted will generate `NameError`s, because `shutil`, `file` and `e` are not defined. Please post a [mcve]. – ForceBru Apr 20 '20 at 16:39
  • Note that [``shutil.move`` is not documented to take path-like arguments](https://docs.python.org/3/library/shutil.html#shutil.move). Also, please post the entire traceback, not just the error message. – MisterMiyagi Apr 20 '20 at 16:54
  • I simply converted the path object to string and it worked. – Amir Charkhi Nov 30 '21 at 12:20

2 Answers2

15

Use the rename function of Path to move a file, if you're using the pathlib module.

ie.

(path / file).rename(path / e.upper())

Otherwise, if you wish to use the shutil module, then you must convert your paths to strings before passing them to shutil.move()

ie.

shutil.move(str(path / file), str(path / e.upper()))
Dunes
  • 37,291
  • 7
  • 81
  • 97
1

Considering file and folders path as string solved this error

shutil.move(str(source_path),str(destination_path))
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39