【问题标题】:Writing into csv file would export in excel wrong写入csv文件会在excel中导出错误
【发布时间】:2017-01-20 07:26:08
【问题描述】:

我在写入 csv 文件时遇到问题。首先,代码中的“列表”将返回一个列表,其中的用户名有很多空白且无法正确显示。其次,一旦我尝试将其写入 csv 文件,我会在 excel 的不同单元格中获取用户名的每个字符。

for i in range(0,33):
    link = (df.link.iloc[i])
    source1 = urllib.request.urlopen(link).read()
    soup1 = bs.BeautifulSoup(source1,'lxml')
    for username in soup1.find_all('div', class_="user-name"):
        lists.append(username.text)
#    for time in soup1.find_all('div',class_="thread-ago"):
example = open('generalinfo.csv','w')
wr = csv.writer(example,quoting = csv.QUOTE_ALL)        
wr.writerows(lists)    
example.close()  

【问题讨论】:

    标签: python export-to-csv writetofile


    【解决方案1】:

    wr.writerows(lists) 需要一个字符串列表的列表。在您的 sn-p 中,它是一个字符串列表。每个字符串(作为一个序列)都被隐式转换为一个字符列表,并且每个字符都写在自己的单元格中。以下是修复方法:

    lists.append([username.text])
    

    【讨论】:

    • 谢谢!你知道如何避免在 python 的列表中出现所有这些空白吗?
    【解决方案2】:

    writerows() 需要列表的列表,试试::

    for username in soup1.find_all('div', class_="user-name"):
        lists.append([username.text])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-18
      • 2018-01-26
      • 2011-04-16
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多