我正在做一个项目,在将文件移动到不同的子文件夹时遇到问题。例如,我在主文件夹中有两个文件,我想读第一行,如果第一行有“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'
有人能解释一下我为什么有问题吗?如有任何建议,将不胜感激
++我还尝试关闭该文件。甚至重新启动计算机,从未打开任何文件。仍然会得到相同的错误
出现错误是因为您试图在
with
语句中移动已打开以供读取的文件。下面通过将调用移动到move_files()
来避免这种情况,因此在关闭文件之前不会调用它发生此错误的原因是,您试图在文件处于活动状态并在
with
语句中读取时移动该文件。如果将if
语句取消缩进一层,则问题应该得到解决。这将关闭文件并允许其移动。代码如下:最简单的解决方案就是在程序中取消插入
if
块尽管如此,我可能甚至不会为这个应用程序使用
with
块,只是:编辑:在我(有点反常)对一行程序的热爱中,if语句可以简化为:
分享和享受
相关问题 更多 >
编程相关推荐