Python: IF filename in list -
i'm trying figure out how go through folder , move files in list. have script creating list of file names, need able take files in folder , move them if in list.
import os, shutil filelist = [] root, dirs, files in os.walk(r'k:\users\user1\desktop\python\new folder'): file in files: if file.endswith('.txt'): filelist.append(file) print filelist source = "k:\\users\\user1\\desktop\\python\\new folder" destination = "k:\\users\\user1\\desktop\\python\\new folder (2)" root, dirs, files in os.walk(r'k:\users\user1\desktop\python\new folder'): file in files: if fname in filelist: shutil.move(source, destination)
i've used other snippets i've found online list created, haven't been able understand how file name variable check if it's in list. appreciated.
if understand question correctly, move text files in 1 folder folder? or want pass name of file on command line , if name in filelist, move folder?
in former case, can reduce code to:
import os, shutil source = r"k:\\users\\user1\\desktop\\python\\new folder" destination = r"k:\\users\\user1\\desktop\\python\\new folder (2)" root, dirs, files in os.walk(source): file in files: if file.endswith('.txt'): shutil.move(os.path.join(root,file), destination)
that move textfiles found in source directory destination directory. there no need keep intermediate list then.
if wanted second case, using commandline string passed argument, filter changing last 2 lines of code above to:
if file == sys.argv[1]: shutil.move(os.path.join(root,file), destination)
remember import sys
then. sys.argv
array contains commandline parameters used when called python script. element 0 name of script, element 1 first parameter use variable in script.
Comments
Post a Comment