简体   繁体   English

导入csv时删除换行符

[英]python - remove line breaks when importing csv

I am trying to import some data from a csv. 我正在尝试从csv导入一些数据。 However, for some reason I have some line breaks at the beginning of some of my data. 但是,由于某些原因,我在某些数据的开头有一些换行符。 I am using this code to import: 我正在使用此代码导入:

import csv

def opencsv():
    with open('static/urls.csv', encoding="utf-8-sig", newline='') as csvfile:
        lines = csv.reader(csvfile, skipinitialspace=True, delimiter=',', quotechar='|')
        for row in lines:
            csvrows = ''.join(row)

It all works fine until there is a line break (I am talking about line break like this '\\n' and not a blank space) in the data that I try to import. 一切正常,直到尝试导入的数据中出现换行符(我说的是这样的换行符'\\ n'而不是空格)。

Whenever there is a line break my csvrows will looke like this 每当有换行符时,我的csvrows就会像这样

cvsrows = '"'

ignoring all the other characters that were initially in the cell of the csv. 忽略最初在csv单元中的所有其他字符。 Any idea how I can get rid of the linebreak when importing? 知道导入时如何摆脱换行符吗?

Does this solve your problem? 这样可以解决您的问题吗?

        import pandas as pd
        df=pd.read_csv(filename).dropna().reset_index().drop(['index'], axis=1)

Also please share a sample of your file as it helps us in recreating the issue and solving it. 另外,请分享您的文件示例,因为它有助于我们重新创建问题并解决问题。

尝试将csvrows = ''.join(row)替换为csvrows = ''.join(row) . csvrows = ''.join(row.strip())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM