Python复制或移动名称在文本文件列表中的文件

时间:2014-02-24 13:23:28

标签: python shutil

任何人都可以告诉我如何将一批文件复制或移动到另一个目录或其他目录。文件的名称位于文本文件中的列表中。我正在研究Windows系统。文本文件包含与此类似的列表:

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

...更多文件名

我已经尝试过readline()来读取文件列表和shutil.move(src,dest)来移动文件,但是不知道如何正确传递src文件而不会出错。任何有关这种或那种方式的建议都会受到赞赏吗?感谢。

我使用只有一个条目的文件列表进行了测试: (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'"

2 个答案:

答案 0 :(得分:1)

你必须将r"c:\test"放在python程序中,因为它是在python中表示文字C:\test的方式。当在文件中读取它们时,每个字符代表自己 所以只是

import shutil

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

应该有效

答案 1 :(得分:0)

你需要转义反斜杠,所以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'