How can i move files from one directory to another?

后端 未结 1 1052
走了就别回头了
走了就别回头了 2021-01-24 09:20

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

相关标签:
1条回答
  • 2021-01-24 09:59

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

    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
    
    0 讨论(0)
提交回复
热议问题