【问题标题】:How to write values to CSV file in two columns using Python 3?如何使用 Python 3 在两列中将值写入 CSV 文件?
【发布时间】:2019-05-16 11:59:42
【问题描述】:

如何在 CSV 文件中写入两列?第一个应该有 data[0],第二个应该有 data[1]

with open('list_of_courses.csv', 'w', newline='', delimiter=',') as f:
    thewriter = csv.writer(f)

    for dept_courses in dept_url_dict.values():
        newpage = requests.get("https://bulletin.temple.edu"+dept_courses)
        courses = BeautifulSoup(newpage.content, 'html.parser')
        courselist = courses.select('p.courseblocktitle')
        print(dept_courses)
        for c in courselist:
            string = c.text
            data = string.split(".")
            thewriter.writerow(data[0]+","+data[1])

我希望 CSV 文件有两列,但目前每个字符都有一列。

【问题讨论】:

标签: python csv


【解决方案1】:

试试这个...

with open('list_of_courses.csv', 'w', newline='', delimiter=',') as f:
   thewriter = csv.writer(f) 
   for dept_courses in dept_url_dict.values():    
       newpage=requests.get("https://bulletin.temple.edu"+dept_courses)
       courses = BeautifulSoup(newpage.content, 'html.parser') 
       courselist = courses.select('p.courseblocktitle')     print(dept_courses) 
       for c in courselist: 
            string = c.text 
            data = string.split(".")          
            thewriter.writerow([data[0],data[1]])


您应该将列表传递给thewriter,而不是字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2016-03-26
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多