我正在尝试使用while循环编写一个监视已定义目录的小脚本。在此过程完成后,此目录中的每个文件或目录都将压缩为RAR并移动到另一个目录
我的问题:每次我将文件或文件夹复制到此目录时,脚本都不会等待并在第二次看到新文件或文件夹时启动该进程。但是当文件或文件夹大于几千字节时,循环会因许可错误而中断
由于我是Python初学者,我不知道使用哪个模块。是否有一个检查模块,以查看该工具要处理的文件或文件夹是否被另一个进程使用?还是我走错了方向?
编辑:添加代码仅用于目录聆听:
watchDir = "L:\\PythonTest\\testfolder\\"
finishedDir = "L:\\PythonTest\\finishedfolders\\"
rarfilesDir = "L:\\PythonTest\\rarfiles\\"
rarExe = "L:\\PythonTest\\rar.exe"
rarExtension = ".rar"
rarCommand = "a"
while True:
dirList = [name for name in os.listdir(watchDir) if os.path.isdir(os.path.join(watchDir,name))]
for entryName in dirList:
if not os.path.exists((os.path.join(finishedDir,entryName))):
sourcePath = os.path.join(watchDir,entryName)
entryNameStripped = entryName.replace(" ", "")
os.chdir(watchDir)
archiveName = rarfilesDir+entryNameStripped+rarExtension
subprocesscall = [rarExe, rarCommand, archiveName, entryName]
subprocess.call(subprocesscall, shell=True)
shutil.move(sourcePath,finishedDir)
当我运行脚本并尝试添加几GB的文件(在以下行中命名为#filename#)时,会出现以下错误:
Creating archive L:\PythonTest\rarfiles\#filename#.rar
Cannot open #filename#
The process cannot access the file, since it's used by another process.
Adding #filename# OK
WARNING: Cannot open 1 file
Done
Traceback (most recent call last):
File "C:\Python34\lib\shutil.py", line 522, in move
os.rename(src, real_dst)
PermissionError: [WinError 5] Access denied: #filepath#
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "L:/Python Test/test.py", line 35, in <module>
shutil.move(sourcePath,finishedDir)
File "C:\Python34\lib\shutil.py", line 531, in move
copytree(src, real_dst, symlinks=True)
File "C:\Python34\lib\shutil.py", line 342, in copytree
raise Error(errors)
shutil.Error: #filepath#
答案 0 :(得分:0)
而不是使用os.listdir,你可以使用os.walk,os.walk产生3元组dirpath(目录路径,文件名(该dirpath中的所有文件),dirnames(dirpath中的所有子目录)
for x,y,z in os.walk('path-of-directory'): do you stuff with x,y,z the three tuples