Warm tip: This article is reproduced from serverfault.com, please click

python-使用lineterminator删除从 pandas 到CSV的最后一条空行

(python - remove last empty line from pandas to csv using lineterminator)

发布于 2020-11-27 08:28:40

我有一个要求,我必须将一些列拆分为第一行,其余的拆分为第二行。

我已经将它们存储在一个数据框中,例如:

columnA   columnB   columnC   columnD
   A         B         C         D

到文本文件sample.txt

A,B
C,D

这是代码:

cleaned_data.iloc[:, 0:1].to_csv("report_csv.txt", encoding='utf-8', index=False, header=False, line_terminator='')
cleaned_data.iloc[:,1:].to_csv("report_csv.txt", encoding='utf-8', index=False, header=False, mode='a', line_terminator='')

它应该按预期生产sample.txt但是,第三行是空的,我不希望它存在。我试过了lineterminator='',它不起作用,''但是例如' ''abc'等。

我敢肯定,比起使用我编写的内容,有更好的方法来生成示例文本文件。我正在寻找其他选择。

不过,如何删除最后一个空行?我正在使用python 3.8

Questioner
user6308605
Viewed
11
Ben 2020-11-29 21:53:20

我无法重现你的问题,但可能是数据框中的字符串包含尾随换行符的情况。我在Linux上运行Pandas 0.23.4

import pandas
print(pandas.__version__)

我使用以下命令创建了我认为你的数据框包含的内容

df = pandas.DataFrame({'colA':['A'], 'colB': ['B'], 'colC':['C'], 'colD':['D']})

要检查单元格的内容,可以使用df['colA'][0]

我需要抓取第一列和第二列的索引是

df.iloc[:, 0:2]

而且我获取CSV的方式不依赖于 lineterminator

df.iloc[:, 0:2].to_csv("report_csv.txt", encoding='utf-8', index=False, header=False)
df.iloc[:,2:].to_csv("report_csv.txt", encoding='utf-8', index=False, header=False, mode='a')

当我跑步时

with open('report_csv.txt','r') as file_handle:
dat = file_handle.read()

'A,B\nC,D\n'dat

要使最后一行没有尾随换行符,请使用 to_string()

with open('output.txt','w') as file_handle:
    file_handle.write(df.iloc[:, 0:2].to_string(header=False,index=False)+"\n")
    file_handle.write(df.iloc[:,2:].to_string(header=False,index=False))

然后我们可以通过运行来验证文件的格式是否符合要求

with open('output.txt','r') as file_handle:
    dat = file_handle.read()

dat包含'A B\nC D'如果空格不是可接受的分隔符,则可以,在写入文件之前将其替换为。