我有一个文本文件,我正在使用 python将其转换为csv。文本文件具有使用多个空格设置的列。我的代码删除了行,将一行中的 2 个空格转换为逗号,然后再次拆分行。当我这样做时,列不对齐,因为有些列的空格比其他列多。如何在我的代码中添加一些内容以删除csv文件中的空白单元格?我尝试将 csv 文件转换为pandas 数据库,但是当我运行时import pandas as pddf = pd.read_csv('old.Csv')delim_whitespace=Truedf.to_csv("New.Csv", index=False)它返回一个错误 ParserError: Error tokenizing data. C error: Expected 40 fields in line 10, saw 42剥离行并拆分它们的代码是import csvtxtfile = 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)
2 回答

白衣染霜花
TA贡献1796条经验 获得超10个赞
一种解决方案是预先声明列名,以强制 pandas 获取具有不同列数的数据。像这样的东西应该工作:
df = pd.read_csv('myfilepath', names = ['col1', 'col2', 'col3'])
您必须自己调整分隔符和列名/列数。

慕村225694
TA贡献1880条经验 获得超4个赞
(编辑)下面的代码应该适用于您的文本文件:
a b c d e
=============================
1 qwerty 3 4 5 6
2 ewer e r y i
3 asdfghjkutrehg c v b n
你可以试试:
import pandas as pd
df = 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 e
0 1 qwerty 3 4 5 6
1 2 ewer e r y i
2 3 asdfghjkutrehg c v b n
添加回答
举报
0/150
提交
取消