Вопрос

As a Python beginner, I'm having real issues moving files around. Below is a script I've finally(!) made work which simply moves select files from a directory of choice to a new folder. For some reason which I cannot fathom, it only worked once, then the destination folder created was really bizarre. At one point it created a 'directory' that was an unknown application with the correct name and at other times it creates a text file using seemingly random files to generate the content - again the file it creates is correctly named.

Here is the relevant script:

#!/usr/bin/python

import os, shutil

def file_input(file_name):                
    newlist = []                                                #create new list
    for names in os.listdir(file_name):                         #loops through directory
        if names.endswith(".txt") or names.endswith(".doc"):    #returns only extensions required    
            full_file_name = os.path.join(file_name, names)     #creates full file path name - required for further file modification
            newlist.append(full_file_name)                      #adds item to list
            dst = os.path.join(file_name + "/target_files")
            full_file_name = os.path.join(file_name, names)
            if (os.path.isfile(full_file_name)):
                print "Success!"
                shutil.copy(full_file_name, dst)

def find_file():
    file_name = raw_input("\nPlease carefully input full directory pathway.\nUse capitalisation as necessary.\nFile path: ")
    file_name = "/root/my-documents"                            #permanent input for testing!
    return file_input(file_name)
    '''try:
        os.path.exists(file_name)
        file_input(file_name)
    except (IOError, OSError):
        print "-" * 15
        print "No file found.\nPlease try again."
        print "-" * 15
        return find_file()'''

find_file()

Can someone please tell me why this script is not reproducible when I delete the folder created and try to run it again and what I can do to make that happen?

I know it's a bit messy, but this is going to part of a larger script and I'm still in first draft stages!!

Many thanks

Это было полезно?

Решение

This works:

import os, shutil

def file_input(file_name):                
    newlist = []                                                #create new list
    for names in os.listdir(file_name):                         #loops through directory
        if names.endswith(".txt") or names.endswith(".doc"):    #returns only extensions required    
            full_file_name = os.path.join(file_name, names)     #creates full file path name - required for further file modification
            newlist.append(full_file_name)                      #adds item to list
            dst = os.path.join(file_name + "/target_files")

            if not os.path.exists(dst):
                os.makedirs(dst)

            full_file_name = os.path.join(file_name, names)
            if (os.path.exists(full_file_name)):
                print "Success!"
                shutil.copy(full_file_name, dst)

def find_file():
    file_name = raw_input("\nPlease carefully input full directory pathway.\nUse capitalisation as necessary.\nFile path: ")
    file_name = "/home/praveen/programming/trash/documents"                            #permanent input for testing!
    return file_input(file_name)

find_file()

You need to check if your copy destination directory actually exists, if not create it. shutil.copy would then copy your file to that directory

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top