Python copies or moves files whose names are listed in a text file

Can someone tell me how to copy or move a batch of files to another directory or other directories. The file name is in the list, which is in the text file. I am working on a windows system. The text file contains a list similar to this:

C:\dir1\dir3\dir4\file1.pdf
C:\dir5\dir6\file2.txt
c:\dir7\dir8\dir9\dir10\file3.pdf

... more file names

I tried readline () to read the list of files and shutil.move (src, dest) to move the files, but I don’t know how to transfer the src file correctly without receiving an error. Any suggestions on this will be appreciated? Thank.

I tested using a list of files in which there was only one entry: (Filetest.txt): C: \ Documents and Settings \ Owner \ My Documents \ movetest.txt

import shutil

# shutil.move(r'C:\Documents and Settings\Owner\My Documents\test4.txt', r'C:\Documents and Settings\Owner\My Documents\Test\test4.txt')

filein = open('filetest.txt', 'r')
line = filein.readline()
name = 'r' + "'" + line[:len(line) - 1] + "'"
shutil.move(name, 'movetest.txt')
filein.close()`

Traceback:

Traceback (most recent call last):
  File "C:\Python33\Lib\shutil.py", line 522, in move
    os.rename(src, real_dst)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'movetest.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Documents and Settings/Owner/My Documents/Python 3 Programs/MoveTest10.py", line 12, in <module>
    shutil.move(name, 'movetest.txt')
  File "C:\Python33\Lib\shutil.py", line 534, in move
    copy2(src, real_dst)
  File "C:\Python33\Lib\shutil.py", line 243, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "C:\Python33\Lib\shutil.py", line 109, in copyfile
    with open(src, 'rb') as fsrc:
OSError: [Errno 22] Invalid argument: "r'C:\\Documents and Settings\\Owner\\My Documents\\movetest.txt'"
+3
source share
2

r"c:\test" python , C:\test python. ,

import shutil

filein = open('filetest.txt', 'r')
line = filein.readline()
name = line[:len(line) - 1]
shutil.move(name, 'movetest.txt')
filein.close()`

+1

, python : :

C:\dir1\dir3\dir4\file1.pdf

:

C:\\dir1\\dir3\\dir4\\file1.pdf

, :

for line in file:
    line = line.replace('\\', '\\\\')

:

In [5]: path='c:\\dir\\file'

In [6]: path.replace('\\','\\\\')
Out[6]: 'c:\\\\dir\\\\file'
0

All Articles