如何让Python的csv.writer和csv.writerows写入下一行,而不是一行在另一行下面

csbfibhn  于 2023-03-11  发布在  Python
关注(0)|答案(1)|浏览(184)

我试图让Python将5行文本写入CSV文件,但要将单个值重写到旁边的单元格中,而不是下面的单元格中。
目前,程序能够写入所有变量,值,因为它想要的,但没有适当的安排。但是,csv.write和csv.writerows不断覆盖从单元格,使其增加值到单元格[A1],然后[A2],而不是[A1],然后[B1]。有没有一个函数,我可以使用,写一切就像例如打印(f”{variable}",end =',')
我对Python很陌生,对不起。
文件名= 'test1.csv'
打开(文件名,模式=“w”)作为文件:writer = csv.编写器(文件)

with open('1.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    categories = data['categories']
    writer.writerow(f"URL,{','.join(categories)}") 
for file in json_files:
    with open(file, 'r', encoding='utf-8') as f:
        data = json.load(f)                                               
        writer.writerow(url)    
    for category in data['categories']:
        scores = data['categories'][category]['score']                                                        
        writer.writerow(f"{scores}")
**# Desired output:
# 
# ,
# 
# URL,performance,accessibility,best-practices,seo,pwa,visibility,security,ads,mobile
# URL, 0.23, 0.56, 0.57, 0.67, 0.31, 0.67, 0.37, 0.54, 0.71,
# URL, 0.53, 0.53, 0.57, 0.8, 0.23, 0.67, 0.5, 0.62, 0.71,
# URL, 1, 1, 0.86, 0.88, 0.58, 0.67, 0.42, 0.38, 1,
# 
# 
# 
# What ive got
# 
# U,R,L,",",p,e,r,f,o,r,m,a,n,c,e,",",a,c,c,e,s,s,i,b,i,l,i,t,y,",",b,e,s,t,-,p,r,a,c,t,i,c,e,s,",",s,e,o,",",p,w,a,",",v,i,s,i,b,i,l,i,t,y,",",s,e,c,u,r,i,t,y,",",a,d,s,",",m,o,b,i,l,e
# 
# URL
# 
# 0,.,2,3
# 
# 0,.,5,6
# 
# 0,.,5,7
# 
# 0,.,6,7
# 
# 0,.,3,1
# 
# 0,.,6,7
# 
# 0,.,3,7
# 
# 0,.,5,4
# 
# 0,.,7,1
# 
# URL
# 
# 0,.,5,3
# 
# 0,.,5,3
# 
# 0,.,5,7
# 
# 0,.,8
# 
# 0,.,2,3
# 
# 0,.,6,7
# 
# 0,.,5
# 
# 0,.,6,2
# 
# 0,.,7,1
# 
# URL
# 
# 1
# 
# 1
# 
# 0,.,8,6
# 
# 0,.,8,8
# 
# 0,.,5,8
# 
# 0,.,6,7
# 
# 0,.,4,2
# 
# 0,.,3,8
# 
# 1
**
xwbd5t1u

xwbd5t1u1#

我假设json文件的结构如下(每个json文件只有一个JSON对象):

{
    "URL": <url_content>,
    "performance": <performance_score>,
    "accessibility": <accessibility_score>,
    ...
}

我想出了这个密码:

import json

files = ["1.json", "2.json"]
output = "output.csv"

if __name__ == "__main__":
    aggregate = []

    for file in files:
        with open(file, "r", encoding="utf-8") as fp:
            curr_data = json.load(fp)
        if len(aggregate) == 0:
            aggregate.append(",".join([f"{key}" for key in curr_data]))
        aggregate.append(",".join([f"{curr_data[key]}" for key in curr_data]))

    with open(output, "w", encoding="utf-8") as file:
        file.write("\n".join(aggregate))

我创建了两个虚拟的json文件:
1.json

{
  "URL": "url1_content",
  "performance": 0.23,
  "accessibility": 0.56
}

2.json

{
  "URL": "url2_content",
  "performance": 0.53,
  "accessibility": 0.53
}

然后创建以下output.csv

URL,performance,accessibility
url1_content,0.23,0.56
url2_content,0.53,0.58

相关问题