如何将文件从一个目录移动到另一个目录? [英] How can i move files from one directory to another?

查看:82
本文介绍了如何将文件从一个目录移动到另一个目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am beginner in python . I want to move some files from one directory to another. I just now i have to use some modules like Os and Shutil. and i write this code but it return an error:

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

请帮帮我

推荐答案

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

This is kind of a wild guess, but I'm pretty sure that this is your problem, so I'll give it a try.

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

Note that os.listdir returns a list of filenames only; it does not include the directory that was the parameter to os.listdir. I.e., you have to tell shutils.move where to find those files! Also, you might have to create the destination directory, if it does not yet exist. Try this:

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

这篇关于如何将文件从一个目录移动到另一个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆