使用python从CSV文件中删除空白单元格

我有一个文本文件,我正在使用 python将其转换为csv。文本文件具有使用多个空格设置的列。我的代码删除了行,将一行中的 2 个空格转换为逗号,然后再次拆分行。当我这样做时,列不对齐,因为有些列的空格比其他列多。如何在我的代码中添加一些内容以删除csv文件中的空白单元格?


我尝试将 csv 文件转换为pandas 数据库,但是当我运行时


import pandas as pd

df = pd.read_csv('old.Csv')


delim_whitespace=True


df.to_csv("New.Csv", index=False)

它返回一个错误 ParserError: Error tokenizing data. C error: Expected 40 fields in line 10, saw 42


剥离行并拆分它们的代码是


import csv


txtfile = r"Old.txt"

csvfile = r"Old.Csv"


with open(txtfile, 'r') as infile, open(csvfile, 'w', newline='') as outfile:    

    stripped = (line.strip() for line in infile)

    replace = (line.replace("  ", ",") for line in stripped if line)

    lines = (line.split(",") for line in replace if infile)

    writer = csv.writer(outfile)

    writer.writerows(lines)


MMMHUHU
浏览 750回答 2
2回答

白衣染霜花

一种解决方案是预先声明列名,以强制 pandas 获取具有不同列数的数据。像这样的东西应该工作:df = pd.read_csv('myfilepath', names = ['col1', 'col2', 'col3'])您必须自己调整分隔符和列名/列数。

慕村225694

(编辑)下面的代码应该适用于您的文本文件:   a               b  c  d  e=============================1  qwerty          3  4  5  62  ewer            e  r  y  i               3  asdfghjkutrehg  c  v  b  n 你可以试试:import pandas as pddf = pd.read_fwf('textfile.txt', delimiter='  ', header=0, skiprows=[1])df.to_csv("New.csv", index=False)print(df)     Unnamed: 0               a  b  c  d  e0           1          qwerty  3  4  5  61           2            ewer  e  r  y  i2           3  asdfghjkutrehg  c  v  b  n
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python