尝试将文件移动到其他位置时出现权限错误

2024-06-06 13:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个项目,在将文件移动到不同的子文件夹时遇到问题。例如,我在主文件夹中有两个文件,我想读第一行,如果第一行有“Job”一词,那么我将移动到子文件夹(main_folder/files/jobs)。我的代码如下所示:

# 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)

所以根据我的研究,我猜这个文件仍然是打开的(?),所以我试着关闭它。然后继续,但不知何故,我在子文件夹中有一个文件,而原始文件仍在主文件夹中。错误如下所示:

Traceback (most recent call last):
  File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.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:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.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'

有人能解释一下我为什么有问题吗?如有任何建议,将不胜感激

++我还尝试关闭该文件。甚至重新启动计算机,从未打开任何文件。仍然会得到相同的错误


Tags: 文件namein文件夹movedirfilesusers
3条回答

出现错误是因为您试图在with语句中移动已打开以供读取的文件。下面通过将调用移动到move_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]:
            move_files(file, 'jobs/')
            print("This is a job related file")
        else:
            print("no")

    return True

发生此错误的原因是,您试图在文件处于活动状态并在with语句中读取时移动该文件。如果将if语句取消缩进一层,则问题应该得到解决。这将关闭文件并允许其移动。代码如下:

# 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

最简单的解决方案就是在程序中取消插入if

# 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)

尽管如此,我可能甚至不会为这个应用程序使用with块,只是:

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

编辑:在我(有点反常)对一行程序的热爱中,if语句可以简化为:

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

分享和享受

相关问题 更多 >