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

Python 2.7 如何将文件从一个目录移动到另一个目录?,python-2.7,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,destinatio

我是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)

请帮帮我这是一种猜测,但我很确定这是你的问题,所以我会试试看

请注意,
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

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

请注意,
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

错误是什么?通过编辑您的问题提供有关它的全部详细信息。错误是什么?通过编辑您的问题提供有关它的全部详细信息。