【发布时间】:2016-12-15 16:46:50
【问题描述】:
所以我在 CSV 文件中有大约 5008 行,总共 5009 行带有标题。我在同一个脚本中创建和编写这个文件。但是当我最后阅读它时,使用 pandas pd.read_csv 或 python3 的 csv 模块并打印 len,它输出 4967。我检查了文件中是否存在任何可能使 python 混淆但没有看到的奇怪字符。所有数据均以逗号分隔。
我也在 sublime 中打开它,它显示 5009 行而不是 4967。
我可以尝试来自 pandas 的其他方法,例如 merge 或 concat,但如果 python 不能正确读取 csv,那就没用了。
这是我尝试过的一种方法。
df1=pd.read_csv('out.csv',quoting=csv.QUOTE_NONE, error_bad_lines=False)
df2=pd.read_excel(xlsfile)
print (len(df1))#4967
print (len(df2))#5008
df2['Location']=df1['Location']
df2['Sublocation']=df1['Sublocation']
df2['Zone']=df1['Zone']
df2['Subnet Type']=df1['Subnet Type']
df2['Description']=df1['Description']
newfile = input("Enter a name for the combined csv file: ")
print('Saving to new csv file...')
df2.to_csv(newfile, index=False)
print('Done.')
target.close()
我尝试的另一种方法是
dfcsv = pd.read_csv('out.csv')
wb = xlrd.open_workbook(xlsfile)
ws = wb.sheet_by_index(0)
xlsdata = []
for rx in range(ws.nrows):
xlsdata.append(ws.row_values(rx))
print (len(dfcsv))#4967
print (len(xlsdata))#5009
df1 = pd.DataFrame(data=dfcsv)
df2 = pd.DataFrame(data=xlsdata)
df3 = pd.concat([df2,df1], axis=1)
newfile = input("Enter a name for the combined csv file: ")
print('Saving to new csv file...')
df3.to_csv(newfile, index=False)
print('Done.')
target.close()
但无论我以何种方式尝试 CSV 文件都是实际问题,python 写入正确但读取不正确。
编辑:最奇怪的部分是我在运行代码时完全没有编码错误或任何错误......
Edit2:在第一个代码示例中尝试使用 nrows 参数对其进行测试,最多可工作 4000 行。当我指定 5000 行时,它只读取 4967。
Edit3:用我的数据手动保存 csv 文件,而不是使用程序编写的文件,它读取了 5008 行。为什么python没有正确写入csv文件?
【问题讨论】:
-
您确定每一行都以正确的换行符结尾吗?你试过
error_bad_lines=True吗? -
您确定源文件不包含任何编码错误吗?你可以用
open()打开它而没有任何错误吗? -
你确定然后在字段中间没有(保护/屏蔽)换行符?
-
@Tommy 是的,我在脚本中编写 CSV 的方式每行数据都以换行符结尾。
-
@DaVinci 当
error_bad_lines=True时会发生什么?
标签: python python-3.x csv pandas