NameError不是用Python中的Json和Pandas定义的



尝试从JSON文件中提取字符串后的特定行,以JSON格式附加数据,然后发送到Dataframe,这是可行的,但现在不行。有人知道为什么我现在会收到NameError吗?

z=json.loads(行(名称错误:未定义名称"行">

import fileinput, re, json
import pandas as pd
p = [
"Test/a",
"Test/b"
]
dir = "/home/****/"
for i,ip in enumerate(p):
t = ip.replace('/', '')
directory = dir + t
found = False
for line in fileinput.input(directory + "/" + t +"_type.json",inplace=True):
if re.match('{"p',line):
found = True
if found:
print(line,end="")
y = {"p":"example"}
z = json.loads(line)
z.update(y)
q = json.dumps(z)
df = pd.read_json(q)
for i, g in df.groupby([
"Apple",
"Bannana"
]):
print(g)

当前,for循环从fileinput.input(directory + "/" + t +"_type.json",inplace=True)获取每个项,并将其放入变量line中。但是,这个变量只在for循环中定义,所以一旦程序离开循环,就不再定义它
根据您希望程序的行为方式,您有几个解决方案,但它们的工作原理基本相同,您只需要选择要执行的内容和时间:

for i,ip in enumerate(p):
t = ip.replace('/', '')
directory = dir + t
found = False
for line in fileinput.input(directory + "/" + t +"_type.json",inplace=True):
if re.match('{"p',line):
found = True
if found:
print(line,end="")
# From there we add 2 levels of indentation in order to execute
# the code if found is true
y = {"p":"example"}
z = json.loads(line)
z.update(y)
q = json.dumps(z)
df = pd.read_json(q)
for i, g in df.groupby([
"Apple",
"Bannana"
]):
print(g)

for i,ip in enumerate(p):
t = ip.replace('/', '')
directory = dir + t
found = False
for line in fileinput.input(directory + "/" + t +"_type.json",inplace=True):
if re.match('{"p',line):
found = True
if found:
print(line,end="")
# From there we add 1 levels of indentation in order to execute
# the code for each iteration of the loop
y = {"p":"example"}
z = json.loads(line)
z.update(y)
q = json.dumps(z)
df = pd.read_json(q)
for i, g in df.groupby([
"Apple",
"Bannana"
]):
print(g)

我希望你会发现这个有用的

最新更新