如何使用python处理输出?
我为修改文本制作了一些脚本 但我无法得出结果。 下面是我的脚本。 我刚开始学习python 我认为我的脚本不起作用,因为如何使用python处理输出?,python,stdout,Python,Stdout,我为修改文本制作了一些脚本 但我无法得出结果。 下面是我的脚本。 我刚开始学习python 我认为我的脚本不起作用,因为f=open('find\u c\u volume\u 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_l
f=open('find\u c\u volume\u 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,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
循环的结果,或者我建议将每行的内容聚合到列表中,然后立即写入
此外,您的“分割线”值存在问题,它始终为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 = []
与传统的open()
函数相比,新的ish(在Python>=3.4中提供)是一种非常简单的文件读写方法。它还非常适合处理类似路径的对象(在Windows和其他操作系统中)
要读取路径上的文件,您可以直接从路径
对象中获取文本
contents = afile.read_text()
content_lines = contents.split('\n')
…并直接编写文本
data = '\n'.join(content_lines)
afile.write_text(data) # overwrites existing file
您也可以使用其open
方法,而不是open
功能:
with afile.open() as f:
dostuff(f)
with
语句是上下文管理器。完成后,它会通过关闭文件自动“清理”(无论发生什么-即使有错误)
以下是从我的另一个答案复制的路径
库的更多信息
为了简化:您可以将任何路径(目录和文件路径对象被视为完全相同)构建为对象,可以是绝对路径对象或相对路径对象。您可以使用原始字符串创建复杂的路径(即,r'string'
),而pathlib
将非常宽容。但是,请注意,有比原始字符串更好的方法来构建路径(请参阅下文)
以下是一些例子:
from pathlib import Path
Path(r'c:\temp\foo.bar') # absolute path
Path(r'c:/temp/foo.bar') # same absolute path
Path('foo.bar') # different path, RELATIVE to current directory
Path('foo.bar').resolve() # resolve converts to absolute path
Path('foo.bar').exists() # check to see if path exists
请注意,如果您在Windowspathlib
上,请原谅您在第二个示例中使用了“错误的斜杠”。请参阅最后的讨论,了解为什么您可能应该始终使用正斜杠
简单显示一些有用的路径(如当前工作目录和用户主页)的工作原理如下:
# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)
# Current directory (absolute):
cwd = Path.cwd()
print(cwd)
# User home directory:
home = Path.home()
print(home)
# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
要向下导航文件树,可以执行以下操作。请注意,第一个对象,home
,是一个路径
,其余只是字符串:
afile = home/'Documents'/'Project Documentation'/'file.txt' # or
afile = home.join('Documents','Project Documentation','file.txt')
通过以下方式检查它是文件还是目录(并且存在):
afile.is_dir()
afile.is_file()
创建一个新的空文件,但不要像这样打开它(以静默方式替换任何现有文件):
要仅在文件不存在时创建该文件,请使用exist\u ok=False
:
try:
afile.touch(exist_ok=False)
except FileExistsError:
# file exists
创建一个新目录(在当前目录下,Path()
),如下所示:
# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)
# Current directory (absolute):
cwd = Path.cwd()
print(cwd)
# User home directory:
home = Path.home()
print(home)
# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
通过以下方式获取路径的文件扩展名或文件名:
afile.suffix # empty string if no extension
afile.stem # note: works on directories too
对路径的整个最后一部分使用name
(如果存在茎和延伸部分):
使用with_name
方法重命名文件(该方法返回相同的路径对象,但使用新文件名):
您可以使用iterdir
,像这样遍历目录中的所有“东西”:
all_the_things = list(Path().iterdir()) # returns a list of Path objects
边栏:反斜杠(\
)
在路径字符串中使用反斜杠时要小心,尤其是以反斜杠结尾的路径。与任何字符串一样,Python即使在原始输入模式下也会将终止的反斜杠作为转义字符读取。请注意:
>>> r'\'
File "<stdin>", line 1
r'\'
^
SyntaxError: EOL while scanning string literal
您正在将制表符放入路径中。这是完全合法的,Python不会抱怨,除非您做了一些事情,使Windows尝试将其转换为真正的Windows路径:
>>> Path('C:\temp').resolve()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\temp'
路径('C:\temp')。解析()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
OSError:[WinError 123]文件名、目录名或卷标语法不正确:“C:\temp”
如果您不知道发生了什么,这也是一个非常隐晦的错误!在处理路径时,最好避免使用反斜杠字符。这是有效的。
我更改字符串内容
非常感谢你
strings = ("Vserver Name:", "Volume Name:", "Aggregate Name:", "Volume Size:", "Available Size:", " Used Size:", " Used Percentage:", "Node name:", "Space Saved by Storage Efficiency:")
with open('find_c_volume_show.txt', 'w') as f:
f.write("Vserver,Volume,Aggregate,Total,Avail,Used,UsedP,Node,Saved\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.strip())
if len(row) == len(strings):
f.write('{}'.format(','.join(row)) +'\n' )
row = []
f.close()
您的输入文本文件可以包含多个卷信息?因此,
FAS8040-ZZZZ
内容只是一个摘录,对吗?执行脚本时收到的错误消息是什么?您收到了吗?[您在顶部打开文件,这应该会起作用或导致异常。]非常感谢。您的代码非常有用。顺便说一句,查找结果有错误。因为文本文件的内容相同使用的大小:30.40GB物理使用的总大小:22.37GB
。我想查看使用的大小内容。我尝试使用re
作为我的代码。但我还没有成功。import sys import re strings=[Vserver Name]、“Volume Name”、“Aggregate Name”、“Volume Size”、“Available Size”、“Used Size”、“Node Name”、“Space Saved by Storage Efficiency”]打开('find_c_Volume_show.txt”、“w')作为f:f.write(“Vserver Name、Volume Name、Aggregate Name、Volume Size、Available Size、Used Size、Node Name、Space Saved\n”),用于打开(“c_volume\u show.txt”):对于字符串中的正则表达式:s=re.search(正则表达式,行)打印
我尝试了仅显示“已用大小”的上限代码。但结果不正确。请帮助。
>>> r'\'
File "<stdin>", line 1
r'\'
^
SyntaxError: EOL while scanning string literal
>>> Path(r'C:\')
File "<stdin>", line 1
Path(r'\')
^
SyntaxError: EOL while scanning string literal
>>> Path('C:\temp')
>>> Path('C:\temp').resolve()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\temp'
strings = ("Vserver Name:", "Volume Name:", "Aggregate Name:", "Volume Size:", "Available Size:", " Used Size:", " Used Percentage:", "Node name:", "Space Saved by Storage Efficiency:")
with open('find_c_volume_show.txt', 'w') as f:
f.write("Vserver,Volume,Aggregate,Total,Avail,Used,UsedP,Node,Saved\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.strip())
if len(row) == len(strings):
f.write('{}'.format(','.join(row)) +'\n' )
row = []
f.close()