【发布时间】:2021-08-20 19:34:34
【问题描述】:
从 Unix 目录中读取多个文件。我正在尝试读取存储在 Unix 文件夹中的多个文件,并在这段文本“input1”之后提取键值对。
每个文件都包含以下格式的数据:-
input1 = {'hostname' : 'host', 'port' : '22', 'basedn' : 'CN=Users', 'bindusername' : 'admin']
Need to read dict and extract Key Value pair and print in below format:
Col1 Col2
xyz 123
abc 456
def 756
path = '/home/var/testfile/'
basepath =os.path.dirname(path)
with os.scandir(basepath) as entries:
for entry in entries:
if entry.is_file():
fn=entry.name
def f(fn):
with open(fn) as f:
for s in f:
data = pd.DataFrame()
key = []
value = []
for k, v in s.items():
key.append(k)
value.append(v)
data["Col1"] = key
data["Col2"] = value
print(data)
Above script does wotk when for a single file , but when i loop to read all the files from the folder , it stucked .
【问题讨论】:
-
到目前为止你尝试了什么?
-
您好,欢迎来到 SO。重要的是要证明您也正在努力解决您的问题,通常是通过发布您的代码的格式化文本版本并突出显示您遇到的问题。如果你这样做,其他人会提供帮助。
-
假设您发布的数据正是文件中的数据,最重要的是使用“单引号”。那么您将要
open()您的文件@ 987654323@ 将内容转换为variable然后ast.literal_eval()即variable给您一个pythondict,您可以使用它来打印带有for循环和variable_as_dict.items()的键和值
标签: python python-3.x pandas dictionary tuples