-1

So I am brand new to python and very stumped. I have a list of files and need to read the files, and find the year '2012' then move those files into a new directory labeled 2012. I have managed to get the list of my files. but have not been able to figure out a way to get them all into a new directory. thank you in advance

    if filename.startswith("ff_"):
        file=open(os.path.join(base, filename),'r')
        for x in file:
            if '2012' in x:   
               print(filename)```
  • You can use `os.makedirs()` to create the 2012 directory and then use `shutil.move()` to move the files to the new location. I like `pathlib`, so personally I'd probably represent paths as `Path` instances and use `Path.mkdir()` instead of `os`. – frippe Jan 09 '22 at 07:31
  • Does this answer your question? [How to move a file in Python?](https://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python) – Julien Jan 09 '22 at 07:55

1 Answers1

0

I hope below code is the solution for your problem. Please note that I have use os.mkdirs() to create new directory. but you can try with Path.mkdir()

I have created four text file. out of 4, three text file have strings 2012. and one text file contains string 2020 and three text file contains 2012

Input files:

  1. ff1.txt (contains string "2012")
  2. ff2.txt (doesn't contains string "2012")
  3. ff_blah1.txt (contains string "2012")
  4. ff_blah1_blah2.txt (contains string "2012")

I have broken down problem statement in steps

  1. find the files which has name starts with "ff"
  2. after finding files, open all the files and search string "2012"
  3. create new folder "2012" if it doesn't exists
  4. move all files that we find at step2 into new created folder "2012"
import os
import shutil

source_path = '/Users/MacJJ271123/Desktop/PY_Script/'
list_of_files = os.listdir(source_path)

def move_file():
    for file in list_of_files:
        if file.startswith("ff"):
            if '2012' in open(file).read():
                if not os.path.exists(os.path.join(source_path, "2012")):
                    os.mkdir(os.path.join(source_path, "2012"))
                shutil.move(os.path.join(source_path,file), os.path.join(source_path,"2012",file))
                print(file)

move_file()

Output:

MacJ271123-MacBook-Air~  # python3 move_files_stack_oveflow.py
ff_blah1_blah2.txt
ff_blah1.txt
ff1.txt
MacJJ271123-MacBook-Air~  # 
user8811698
  • 118
  • 1
  • 7