For example: Question, moving a folder (T061RR7N1) containing a Specific file (ReadCMI), to folder: C:\\...\DUT0

Jason Friedman jsf80238 at gmail.com
Wed Jan 27 22:33:48 EST 2021


>
>
> for path, dir, files in os.walk(myDestinationFolder):
> # for path, dir, files in os.walk(destfolder):
>     print('The path is %s: ', path)
>     print(files)
>     os.chdir(mySourceFolder)
>     if not os.path.isfile(myDestinationFolder + file):
>     #  if not os.path.isfile(destfolder + file):
>         print('The file is %s: ', file)
>         shutil.copytree(mySourceFolder, myDestinationFolder)
>         #  os.rename(path + '\\' + file, myDestinationFolder + file)
>         #  os.rename(path + '\\' + file, destfolder + file)
>         os.rename(path + '\\' + file, myDestinationFolder + file)
>     elif os.path.isfile(myDestinationFolder + file):
>         #  os.rename(path + '\\' + file, destfolder + file)
>         shutil.copytree(mySourceFolder, myDestinationFolder)
> So I would very much appreciate your ideas on the above
> statements!Because...I think I've got the wrong function (os.path.isfile),
> when I should be (s/b) using a stepped approach!Note: program allows input
> of ID = T061RR7N1 (for example)1) find the folder containing "file": where
> folder = T061RR7N1, and file is "ReadCMI"; if TRUE, shutil.copytree
> C:\\...\T061RR7N1\ReadCMI (TO) C:\\...\DUT[?], where [?] is a num from 0 -
> 15.2) append to C:\\...\DUT[?]\T061RR7N1, which contains "ReadCMI"!
>
> and would you mind telling me why this works (in every example I've found
> on the internet): r'C:\\anyfolder\\anyotherfolder\\'...what does the "r"
> signify? If it's 'read', why can't I use the 'a' for append?
>

A few answers and then a question ...

"r" in this context is a raw literal, see for example
https://www.journaldev.com/23598/python-raw-string.

And you probably don't need it. Python and Windows are happy with
"c:/path/to/file.txt" for a file path.
Some of your code might look end up looking like:
full_path = parent + "/" + file

See also the os.path.join method (
https://docs.python.org/3/library/os.path.html#os.path.join) and the
pathlib module (
https://docs.python.org/3/library/pathlib.html#module-pathlib).

If you truly want to move the folder, as opposed to copying it, you can use
shutil.move.

Does the target folder already exist? What is the rule for determining what
the target folder should be named?


More information about the Python-list mailing list