gpt4 book ai didi

python - 如何使用python进行输出?

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:46 25 4
gpt4 key购买 nike

我制作了一些修改文本的脚本。

但我无法得出结果。下面是我的脚本。我刚刚开始学习Python。

我认为我的脚本不起作用,因为 f = open('find_c_volume_show.txt', 'w')

请帮助我。

import sys
from itertools import islice

def next_n_lines(file_opened, N):
return [x.strip() for x in islice(file_opened, N)]

field_line = 1
num = 0
N = 9
split_line = field_line / N

strings = ("Vserver", "Volume Name", "Used Size", "Available Size", "Volume Size", "Aggregate Name", "Space Saved by Storage Efficiency")
f = open('find_c_volume_show.txt', 'w')
for line in open("c_volume_show.txt"):
if any(s in line for s in strings):
field1,field2 = line.strip().split(':')
field_line += 1
f.write(field2 + '\n')
f.close()

f = open('find_c_volume_show.txt', 'w')
f.write("Vserver,Volume Name,Aggregate Name,Volume Size,Available Size,Used Size,Space Saved\n")
with open('find_c_volume_show.txt', 'w') as result:
while num < split_line:
num += 1
lines = next_n_lines(result, N)
f.write('{}'.format(','.join(lines)) +'\n' )
f.close()

下面是我的文本文件。文本文件有多个数据。

                                   Vserver Name: FAS8040-ZZZZ
Volume Name: vol0
Aggregate Name: Node1_aggr0
Volume Size: 466.6GB
Available Size: 436.2GB
Filesystem Size: 466.6GB
Total User-Visible Size: 466.6GB
Used Size: 30.40GB
Used Percentage: 6%
Node name: FAS8040-ZZZZ
Space Saved by Storage Efficiency: 0B
Percentage Saved by Storage Efficiency: 0%
Space Saved by Deduplication: 0B
Space Saved by Compression: 0B
Percentage Space Saved by Compression: 0%
Total Physical Used Size: 22.37GB

我想要如下所示的结果。

Vserver,Volume Name,Aggregate Name,Volume Size,Available Size,Used Size,Space Saved
FAS8040-ZZZZ,vol0,Node1_aggr0,466.6GB,435.7GB,30.92GB,0B
FAS8040-YYYY,vol0,Node2_aggr0,466.6GB,428.7GB,37.91GB,0B
FAS8040-XXXX,vol0,Node2_aggr0,466.6GB,428.7GB,37.91GB,0B

最佳答案

问题是,每次使用 open(filename,'w') 打开文件时,它都会被删除。您可以使用不同名称的“临时”文件来存储第一个 for 循环的结果,或者我建议将每行的内容聚合到列表中,然后立即写入。

此外,您的“split_line”值有问题,它始终为0。我猜您的意思是len(strings)

这是一个代码:

import sys

strings = ("Vserver", "Volume Name", "Used Size", "Available Size", "Volume Size", "Aggregate Name", "Space Saved by Storage Efficiency")

with open('find_c_volume_show.txt', 'w') as f:
f.write("Vserver,Volume Name,Aggregate Name,Volume Size,Available Size,Used Size,Space Saved,Snapshot,Total Used Size\n")
row = []
for line in open("c_volume_show.txt"):
if any(s in line for s in strings):
field1,field2 = line.strip().split(':')
row.append(field2)
print(row)
if len(row) == len(strings):
f.write('{}'.format(','.join(row)) +'\n' )
print(row)
row = []

关于python - 如何使用python进行输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45300478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com