- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个看起来像这样的文件:
它们被放置在
~/ansible-environments/aws/random_name_1/inventory/group_vars/all
~/ansible-environments/aws/random_name_2/inventory/group_vars/all
~/ansible-environments/aws/random_name_3/inventory/group_vars/all
我写道:
import os
import sys
rootdir='/home/USER/ansible-environments/aws'
#print "aa"
for root, subdirs, files in os.walk(rootdir):
for subdir in subdirs:
all_path = os.path.join(rootdir, subdir, "inventory", "group_vars", "all")
if not os.path.isfile(all_path):
continue
try:
with open(all_path, "r") as f:
all_content = f.readlines()
except (OSError, IOError):
continue # ignore errors
csv_line = [""] * 3
for line in all_content:
if line[:9] == "isv_alias:":
csv_line[0] = line[7:].strip()
elif line[:21] == "LMID:":
csv_line[1] = line[6:].strip()
elif line[:17] == "products:":
csv_line[2] = line[10:].strip()
if all(value != "" for value in csv_line):
with open(os.path.join("/home/nsingh/nishlist.csv"), "a") as csv:
csv.write(",".join(csv_line))
csv.write("\n")
我只需要 LMIT、isv_alias、以下格式的产品:
alias,LMIT,product
bloodyhell,80,rms_scl
something_else,434,some_other_prod
最佳答案
这里存在三个问题:
首先使用os.listdir()
查找以下内容~/ansible-environments/aws
,然后构建预期的路径每个 using 内的 inventory/group_vars
目录os.path.join()
,并查看哪些确实存在。然后列出那些确实存在的目录的内容,并假设所有里面的文件(例如all
)是键值文件。这个例子该答案末尾的代码假设所有文件都可以找到了这个方法;如果他们不能,你可能需要调整这个例子使用 os.walk() 或其他方法查找文件的代码。
每个键值文件都是一系列行,其中每一行都是一个键和值以冒号分隔(":"
)。您使用搜索的方法对于子字符串(运算符in
)将失败,例如, key 包含字符串“LMIT”。相反,在冒号处分割线。表达式 line.split(":", 1)
在第一个位置分割行冒号,但不包括后续冒号,以防值本身具有冒号。然后从键和值中去除多余的空格,并构建一个键和值的字典。
现在选择您要保留的 key 。一旦你解析完每一个文件,从中查找字典中的关联值文件,并从中构建一个列表。然后添加值列表从此文件到所有文件的值列表的列表,以及使用 csv.writer
将列表列表写为 CSV 文件。
它可能看起来像这样:
#!/usr/bin/env python2
from __future__ import with_statement, print_function, division
import os
import csv
def read_kv_file(filename):
items = {}
with open(filename, "rU") as infp:
for line in infp:
# Split at a colon and strip leading and trailing space
line = [x.strip() for x in line.split(":", 1)]
# Add the key and value to the dictionary
if len(line) > 1:
items[line[0]] = line[1]
return items
# First find all random names
outer_dir = os.path.expanduser("~/ansible-environments/aws")
random_names = os.listdir(outer_dir)
inner_dirs = [
os.path.join(outer_dir, name, "inventory/group_vars")
for name in random_names
]
# Now filter it to those directories that actually exist
inner_dirs = [name for name in inner_dirs if os.path.isdir(name)]
wanted_keys = ["alias", "LMIT", "products"]
out_columns = ["alias", "LMIT", "product"]
# Collect key-value pairs from all files in these folders
rows = []
for dirname in inner_dirs:
for filename in os.listdir(dirname):
path = os.path.join(dirname, filename)
# Skip non-files in this directory
if not os.path.isfile(path):
continue
# If the file has a non-blank value for any of the keys of
# interest, add a row
items = read_kv_file(path)
this_file_values = [items.get(key) for key in wanted_keys]
if any(this_file_values):
rows.append(this_file_values)
# And write them out
with open("out.csv", "wb") as outfp:
writer = csv.writer(outfp, "excel")
writer.writerow(out_columns)
writer.writerows(rows)
关于python - 无法以 CSV 格式剥离和存储某些文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42288538/
有没有一种快速的方法(无需显式循环遍历字符串中的每个字符)并剥离或保留它。在 Visual FoxPro 中,有一个函数 CHRTRAN() 可以很好地完成这项工作。它是 1:1 字符替换,但如果替换
在 python/pandas 中清理多类型数据框的值,我想修剪字符串。我目前正在按照两个说明进行操作: import pandas as pd df = pd.DataFrame([[' a '
通常情况下,我正在编写剥离新类型的唯一构造函数的函数,例如在以下函数中返回不是 Nothing 的第一个参数: process (Pick xs) = (\(First x) -> x) . mcon
我正在尝试逐渐将 AOSP 从其默认应用程序中剔除。但是我想知道我要应用的方法是否是正确 并且是最有效 . 在查看了这样做的方法后,我来到了以下 方法: (示例应用程序 - “package_name
使用时 hg log --template "{date|isodate} --- {rev}:{node|short} --- ... " 2011-10-07 19:25 -0400 --- 1:
我想在 mySQL 中创建数据库位置记录。我在选择框中有以下 html 字符串: Aka AkaArarimuAwhituBombayBuckland '> 我不想在数据库中手动输入记录,而是想去掉
我目前正在开发一个 Android 项目,其中我使用 Android NDK 用 C 语言进行一些计算。 只要我不运行 proguard,我的应用程序就可以正常工作,但是当我运行时,“reportPr
我想要一个通用的 .js 文件,对于页面上遇到的每个 form,在提交时,它会从所有 textarea、 中删除 HTML input 和 select 元素。我觉得我缺少一个基本技巧。 $("for
我正在尝试编写一个简单的 Python 脚本,它将文本文件作为输入,删除每个非文字字符,并将输出写入另一个文件中。通常我会采取两种方式: 使用正则表达式结合 re.sub 将每个非字母字符替换为空字符
我敢肯定这个问题以前有人问过,但我已经看过了,但找不到答案,或者我只是做错了什么。 HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.Htm
我有这行代码: var newmsg = $('' + ""+dateFormat(timesp)+ " | " + pseudo + ' : '); newmsg.find(".msg").text
我正在尝试从 Windows 路径中删除前缀。我尝试使用 strip_prefix 来做到这一点方法,但它失败了。您可以在 Rust Playground 上试用.即使在 RUST_BACKTRACE
使用这个 question ,我正在试验 substr 和 strrpos,但似乎无法正确处理。 我有一个来自 MySQL 数据库的名称列,其中包含名字和姓氏,如下所示: Doe, Jane A 现有
好的,我如何使用正则表达式删除 http AND/OR www 只是为了让 http://www.domain.com/ 进入 domain.com 假设 x 是任何类型的 TLD 或 cTLD 输入
我正在尝试从 this website 中抓取项目. 项目是:品牌、型号和价格。由于页面结构的复杂性,spider 使用了 2 个 xpath 选择器。 品牌和型号商品来自同一个 xpath,价格来自
这个问题在这里已经有了答案: 关闭 11 年前。
我有一个包含一些 html 标签的字符串,如下所示: " This is a test " 我想去掉标签之间的所有多余空格。我尝试了以下方法: In [1]: import re In [
我目前有一个 URL 列表 http://www.website.com/dynamic/download.ashx?id=123/12/12345 http://www.website.com/dy
我环顾四周,找不到一种简单/单行的方法来去除 numpy 数组中的空格:: print(type(p)) print(p) [{' SPL', 'GPU', 'bcc'} {'ANZ ', 'ROI
我有一个自定义共享点应用程序,其安全模型取决于 HTTP header 。当从移动设备发出请求时,每个请求都会添加一个名为 HTTP_RIM_DEVICE_EMAIL 的 http header 。我
我是一名优秀的程序员,十分优秀!