如何将文件从一个目录移动到另一个目录?

时间:2014-11-26 14:19:45

标签: python-2.7

我是python的初学者。我想将一些文件从一个目录移动到另一个目录。 我刚才必须使用像Os和Shutil这样的模块。我写这个代码,但它返回一个错误:

import shutil
import os
source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"
for files in source:
    if files.endswith(".txt"):
        shutil.move(files,destination)

请帮帮我

1 个答案:

答案 0 :(得分:2)

这是一种疯狂的猜测,但我很确定这是你的问题,所以我会试一试。

请注意os.listdir仅返回文件名列表;它不包括作为os.listdir参数的目录。即,你必须告诉shutils.move在哪里找到这些文件!此外,您可能必须创建目标目录(如果它尚不存在)。试试这个:

import shutil, os
source = "/tmp/"
destination = "/tmp/newfolder/"
if not os.path.exists(destination):
    os.makedirs(destination)                 # only if it does not yet exist
for f in os.listdir(source):
    if f.endswith(".txt"):
        shutil.move(source + f, destination) # add source dir to filename