从 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 .
答案 0 :(得分:0)
import pandas as pd
dic = {'xyz':'123' , 'abc':'456','def':'765'}
data = pd.DataFrame()
key = []
value = []
for k, v in dic.items():
key.append(k)
value.append(v)
data["Col1"] = key
data["Col2"] = value
print(data)
答案 1 :(得分:0)
试试这个?
import pandas as pd
dic1={'xyz':'123' , 'abc':'456','def':'765'}
data = pd.DataFrame()
data['Col1']=[val for val,key in dic1.items()] #=== All keys in dic1
data['Col2']=[key for val,key in dic1.items()] #=== All Values in dic1
print(data)
印刷品:
Col1 Col2
0 xyz 123
1 abc 456
2 def 765