skip to Main Content

I’m doing a project and I’m having problems moving files into different subfolders. So for example, I have 2 files in the main folder, I want to read the first line, and if the first line has the word "Job", then I will move to the subfolder (main_folder/files/jobs). My code looks like this:

# Get all file names in the directory
def file_names():
    files = [file for file in listdir(source_dir) if file.endswith('csv')]
    return files

# Read files and separate them
def categorize_files(files):
    for file in files:
        with open(file, mode='r', encoding='utf8') as f:
            text = f.readline().split(",")
            if 'Job ID' in text[0]:
                ## Problem Here ##
                move_files(file, 'jobs/')
                f.close()
                print("This is a job related file")
            else:
                print("no")

    return True

# Move files
def move_files(file_name, category):
    print(file_name)
    print(category)
    return shutil.move(source_dir + file_name, destination_dir + category + file_name)

So from my research, I’m guessing the file is still open (?) so I tried closing it. And move on, but somehow I end up having one file in the subfolder, and the original files still in the main folder. The error looks like this:

Traceback (most recent call last):
  File "C:UsersMuffinAppDataLocalProgramsPythonPython37-32libshutil.py", line 557, in move
    os.rename(src, real_dst)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' -> 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/files/jobs/file_14.csv'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 38, in <module>
    categorize_files(files)
  File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 22, in categorize_files
    move_files(file, 'jobs/')
  File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 35, in move_files
    return shutil.move(source_dir + file_name, destination_dir + category + file_name)
  File "C:UsersMuffinAppDataLocalProgramsPythonPython37-32libshutil.py", line 572, in move
    os.unlink(src)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv'

Can someone please explain why I’m having a problem? Any advice will be greatly appreciated.

++ I also tried closing the file. And even restart the computer and never opened any files. Still get the same error..

4

Answers


  1. Your file is being Used, Just close the program that it uses in the Taskmanager.

    Login or Signup to reply.
  2. You’re getting the error because you’re trying to move move the file that you have open for reading inside the with statement. The following avoids that by moving the call to move_files() so it isn’t called until the file has been closed.

    # Read files and separate them
    def categorize_files(files):
        for file in files:
            with open(file, mode='r', encoding='utf8') as f:
                text = f.readline().split(",")
            if 'Job ID' in text[0]:
                move_files(file, 'jobs/')
                print("This is a job related file")
            else:
                print("no")
    
        return True
    
    Login or Signup to reply.
  3. The error happens because you are trying to move a file while it is active and being read inside the with statement. The problem should be fixed if you un-indent the if statement by one layer. This should close the file and allow it to be moved. Here is the code:

    # Read files and separate them
    def categorize_files(files):
        for file in files:
            with open(file, mode='r', encoding='utf8') as f:
                text = f.readline().split(",")
            if 'Job ID' in text[0]:
                ## Problem Here ##
                move_files(file, 'jobs/')
                f.close()
                print("This is a job related file")
            else:
                print("no")
    
        return True
    
    Login or Signup to reply.
  4. The easiest solution is just to unindent the if block in your program.

    # Get all file names in the directory
    def file_names():
        files = [file for file in listdir(source_dir) if file.endswith('csv')]
        return files
    
    # Read files and separate them
    def categorize_files(files):
        for file in files:
    
            with open(file, mode='r', encoding='utf8') as f:
                text = f.readline().split(",")
    
            if 'Job ID' in text[0]:
                ## Problem Here ##
                move_files(file, 'jobs/')
                f.close()
                print("This is a job related file")
            else:
                print("no")
    
        return True
    
    # Move files
    def move_files(file_name, category):
        print(file_name)
        print(category)
        return shutil.move(source_dir + file_name, destination_dir + category + file_name)
    

    Although, I probably wouldn’t have even used a with block for this application, just:

    text = open(file, mode='r', encoding='utf8').readline().split(",")
    

    Edit: In my (somewhat perverse) love of one liners, the if statement could be reduced to:

    if 'Job ID' in open(file, mode='r', encoding='utf8').readline().split(",")[0]:
    

    Share and Enjoy!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search