我无法弄清楚如何将所有.log和.txt文件移动到某个文件夹中,并将其子目录移动到新文件夹中。我理解如何使用shutil移动一个文件。但是,我试图使用一个循环,但没有成功,移动所有。有人可以帮我弄这个吗?谢谢......
import os, os.path
import re
def print_tgzLogs (arg, dir, files):
for file in files:
path = os.path.join (dir, file)
path = os.path.normcase (path)
defaultFolder = "Log_Text_Files"
if not defaultFolder.endswith(':') and not os.path.exists('c:\\Extracted\Log_Text_Files'):
os.mkdir('C:\\Extracted\\Log_Text_Files')
if re.search(r".*\.txt$", path) or re.search(r".*\.log$", path):
os.rename(path, 'C:\\Extracted\\Log_Text_Files')
print path
os.path.walk('C:\\Extracted\\storage', print_tgzLogs, 0)
以下是追溯错误:
Traceback (most recent call last):
File "C:\SQA_log\scan.py", line 20, in <module>
os.path.walk('C:\\Extracted\\storage', print_tgzLogs, 0)
File "C:\Python27\lib\ntpath.py", line 263, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 263, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 263, in walk
walk(name, func, arg)
File "C:\Python27\lib\ntpath.py", line 259, in walk
func(arg, top, names)
File "C:\SQA_log\scan.py", line 16, in print_tgzLogs
os.rename(path, 'C:\\Extracted\\Log_Text_Files')
WindowsError: [Error 183] Cannot create a file when that file already exists
答案 0 :(得分:1)
根据回溯,日志文件已经存在。 os.rename
的Python文档说:
在Windows上,如果 dst 已存在,则会引发OSError [...] 。
现在你可以:
os.remove(path)
如果您希望自动删除文件,代码将如下所示(请注意,我根据utdemir的建议将您的正则表达式替换为python endswith
):
import os, os.path
def print_tgzLogs (arg, dir, files):
for file in files:
path = os.path.join (dir, file)
path = os.path.normcase (path)
defaultFolder = "Log_Text_Files"
if not defaultFolder.endswith(':') and not os.path.exists('c:\\Extracted\Log_Text_Files'):
os.mkdir('C:\\Extracted\\Log_Text_Files')
if path.endswith(".txt") or path.endswith(".log"):
if os.path.exists('C:\\Extracted\\Log_Text_Files\\%s' % file):
os.remove('C:\\Extracted\\Log_Text_Files\\%s' % file)
os.rename(path, 'C:\\Extracted\\Log_Text_Files\\%s' % file)
print path
os.path.walk('C:\\Extracted\\storage', print_tgzLogs, 0)
答案 1 :(得分:1)
看起来好像在尝试使用
os.rename(path, 'C:\\Extracted\\Log_Text_Files')
将文件路径移动到目录C:\ Extracted \ Log_Text_Files中,但重命名不起作用:它将尝试创建一个名为C:\ Extracted \ Log_Text_Files的新文件。你可能想要更像这样的东西:
os.rename(path, os.path.join('C:\\Extracted\\Log_Text_Files',os.path.basename(path))