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)

4
  • 1
    Please show the full stack trace, what you have there is not enough Commented Apr 20, 2020 at 16:35
  • 1
    The code you posted will generate NameErrors, because shutil, file and e are not defined. Please post a minimal reproducible example. Commented Apr 20, 2020 at 16:39
  • Note that shutil.move is not documented to take path-like arguments. Also, please post the entire traceback, not just the error message. Commented Apr 20, 2020 at 16:54
  • I simply converted the path object to string and it worked. Commented Nov 30, 2021 at 12:20

2 Answers 2

16

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()))
Sign up to request clarification or add additional context in comments.

Comments

1

Considering file and folders path as string solved this error

shutil.move(str(source_path),str(destination_path))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.