使用必需的列python将所有pcap文件转换为csv [英] Convert all pcap file to csv with required columns python
问题描述
我需要将所有输出CSV文件写入另一个文件夹.例如,如果.pcap
文件位于子文件夹Sub1
,Sub2
中.并且Sub1
具有a1.pcap
和a2.pcap
. Sub2具有b1.pcap
和b2.pcap
.
I need to write all the output CSV files to a different folder. For example if .pcap
files were in subfolders Sub1
, Sub2
. And Sub1
has a1.pcap
and a2.pcap
. Sub2 has b1.pcap
and b2.pcap
.
我需要将输出CSV文件写入与上述名称相同的文件夹中. Sub1
,Sub2
,则Sub1
应该具有a1.csv
,a2.csv
. Sub2
应该具有b1.csv
,b2.csv
.
I need my output CSV files to get written into a folder with the same names as above. Sub1
, Sub2
, then Sub1
should have a1.csv
, a2.csv
. Sub2
should have b1.csv
, b2.csv
.
我该怎么办?
我收到以下错误:
outputdir = startdir / "Outcsv"
TypeError: unsupported operand type(s) for /: 'str' and 'str'
代码是:
import os
startdir= '/root/Desktop/TTT'
suffix= '.pcap'
outputdir = startdir / "Outcsv"
for root,dirs, files, in os.walk(startdir):
for name in files:
if name.endswith(suffix):
filename = os.path.join(root,name)
output_filename = outputdir / filename.relative_to(startdir)
cmd = 'tshark -r {} -T fields -e frame.number -e frame.time_relative -e wlan.sa -e wlan.da -e wlan.ta -e wlan.ra -e frame.time_delta_displayed -e frame.len -E header=y -E separator=, -E quote=d -E occurrence=f > {}.csv'
final_cmd = cmd.format(filename, output_filename)
os.system(final_cmd)
推荐答案
如果要在其他位置重新创建文件夹结构,则需要确保已创建文件夹.可以使用os.makedirs()
命令来完成.可以通过使用比startdir
更深的任何路径来确定子文件夹的结构.然后可以将其附加到您的outputdir
位置.
If you are trying to recreate a folder structure at a different location you will need to ensure that the folders are created. This can be done using the os.makedirs()
command. The subfolder structure can be determined by using any path deeper than startdir
. This can then be appended onto your outputdir
location.
也可以使用os.path.splitext()
替换文件扩展名.
The file extension can also be replaced by using os.path.splitext()
.
例如:
import os
startdir = '/root/Desktop/TTT'
suffix= '.pcap'
outputdir = os.path.join(startdir, "Outcsv")
for root, dirs, files, in os.walk(startdir):
for name in files:
if name.lower().endswith(suffix):
sub_folders = root[len(startdir)+1:]
input_filename = os.path.join(root, name)
output_path = os.path.join(outputdir, sub_folders)
os.makedirs(output_path, exist_ok=True) # Ensure the output folder exists
output_filename = os.path.join(output_path, os.path.splitext(name)[0] + '.csv')
cmd = 'tshark -r {} -T fields -e frame.number -e frame.time_relative -e wlan.sa -e wlan.da -e wlan.ta -e wlan.ra -e frame.time_delta_displayed -e frame.len -E header=y -E separator=, -E quote=d -E occurrence=f > {}'
final_cmd = cmd.format(input_filename, output_filename)
print(final_cmd)
os.system(final_cmd)
这篇关于使用必需的列python将所有pcap文件转换为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!