如何使用 os.system 使用外部 python 脚本一次转换文件夹中的所有文件

How to use os.system to convert all files in a folder at once using external python script

我设法找到了使用外部脚本将文件从一个文件扩展名转换为另一个文件扩展名(.evtx 到 .xml)的方法。以下是我正在使用的:

os.system("file_converter.py file1.evtx > file1.xml")

这使用我调用的外部脚本 (file_converter.py) 成功地将文件从 .txt 转换为 .xml。

我现在正试图找到一种方法,如何使用 'os.system' 或者另一种方法一次转换多个文件,我希望我的程序深入到一个文件夹中并转换我拥有的所有 10 个文件一次都为 .xml 格式。

我的问题是这怎么可能,因为 os.system 只需要一个参数,我不确定如何让它通过目录定位,因为不像我转换的第一个文件在我的标准主目录,但我想用这 10 个文件访问的文件夹在另一个文件夹内,我试图找到一种方法来解决这个问题并立即完成转换,我还希望文件名对于每个单独的文件保持相同,唯一的区别是“.xml”从末尾的“.evtx”更改为“.

文件 "file_converter.py" 可从 here

下载
import os, sys

DIR = "D:/Test"

# ...or as a command line argument

DIR = sys.argv[1]

for f in os.listdir(DIR):
    path = os.path.join(DIR, f)

    name, ext = os.path.splitext(f)

    if ext == ".txt":
        new_path = os.path.join(DIR, f"{name}.xml")    

        os.rename(path, new_path)

遍历目录,并将所有文本文件更改为 XML。

import threading
import os

def file_converter(file):
    os.system("file_converter.py {0} > {1}".format(file, file.replace(".evtx", ".xml")))

base_dir = "C:\Users\carlo.zanocco\Desktop\test_dir\"

for file in os.listdir(base_dir):
    threading.Thread(target=file_converter, args=(file,)).start()

这是我的示例代码。 您可以生成多个线程来运行 操作"concurrently"。该程序将检查目录中的所有文件并进行转换。

编辑python2.7版本

既然我们有更多关于您想要什么的信息,我可以帮助您。 这个程序可以同时处理一个文件夹中的多个文件,它也检查子文件夹。

import subprocess
import os

base_dir = "C:\Users\carlo.zanocco\Desktop\test_dir\"
commands_to_run = list()

#Search all files 
def file_list(directory):
    allFiles = list()
    for entry in os.listdir(directory):
        fullPath = os.path.join(directory, entry)
        #if is directory search for more files
        if os.path.isdir(fullPath):
            allFiles = allFiles + file_list(fullPath)
        else:
            #check that the file have the right extension and append the command to execute later
            if(entry.endswith(".evtx")):
                commands_to_run.append("C:\Python27\python.exe file_converter.py {0} > {1}".format(fullPath, fullPath.replace(".evtx", ".xml")))

    return allFiles

print "Searching for files"
file_list(base_dir)
print "Running conversion"
processes = [subprocess.Popen(command, shell=True) for command in commands_to_run]
print "Waiting for converted files"
for process in processes:
    process.wait()
print "Conversion done"

subprocess模块​​有两种使用方式:

  1. subprocess.Popen: 它运行 进程并继续执行
  2. subprocess.call:它运行进程并等待它,这个函数return退出状态。此值为零表示进程成功终止

编辑python3.7版本

如果您想解决所有问题,只需在您的程序中实施您从 github 分享的代码。您可以轻松地将其实现为函数。

import threading
import os

import Evtx.Evtx as evtx
import Evtx.Views as e_views

base_dir = "C:\Users\carlo.zanocco\Desktop\test_dir\"

def convert(file_in, file_out):
    tmp_list = list()
    with evtx.Evtx(file_in) as log:
        tmp_list.append(e_views.XML_HEADER)
        tmp_list.append("<Events>")
        for record in log.records():
            try:
                tmp_list.append(record.xml())
            except Exception as e:
                print(e)
        tmp_list.append("</Events>")

    with open(file_out, 'w') as final:
        final.writelines(tmp_list)

#Search all files 
def file_list(directory):
    allFiles = list()
    for entry in os.listdir(directory):
        fullPath = os.path.join(directory, entry)
        #if is directory search for more files
        if os.path.isdir(fullPath):
            allFiles = allFiles + file_list(fullPath)
        else:
            #check that the file have the right extension and append the command to execute later
            if(entry.endswith(".evtx")):
                threading.Thread(target=convert, args=(fullPath, fullPath.replace(".evtx", ".xml"))).start()

    return allFiles

print("Searching and converting files")
file_list(base_dir)

如果你想显示你生成的文件,只需像上面那样编辑:

def convert(file_in, file_out):
    tmp_list = list()
    with evtx.Evtx(file_in) as log:
        with open(file_out, 'a') as final:
            final.write(e_views.XML_HEADER)
            final.write("<Events>")
            for record in log.records():
                try:
                    final.write(record.xml())
                except Exception as e:
                    print(e)
            final.write("</Events>")

更新

如果您想在转换后删除“.evtx”文件,只需在 convert 函数末尾添加以下行即可:

try:
    os.remove(file_in)
except(Exception, ex):
    raise ex

这里你只需要使用try .. except因为你运行线程只有当输入值是一个文件。 如果文件不存在,这个函数会抛出异常,所以需要先检查os.path.isfile()