【问题标题】:Data being written in a single line in some csv file在某些 csv 文件中以单行形式写入数据
【发布时间】:2017-08-17 17:46:14
【问题描述】:

我编写了一些代码来从“pdf”文件的特定页面读取数据,并使用 python 将其写入 csv 文件。它只是部分地完成了它的工作。但是,在将数据写入 csv 文件时,它会将这些数据写入一行而不是常规模式。我应该如何修改我的脚本以达到目的?提前致谢。

这是我迄今为止尝试过的:

import csv
from PyPDF2 import PdfFileReader

outfile = open("conversion.csv",'w', newline='')
writer = csv.writer(outfile)

infile = open('some.pdf', 'rb')
reader = PdfFileReader(infile)
contents = reader.getPage(7).extractText().split('\n')
writer.writerow(contents)

print(contents)
infile.close()

pdf中的数据如下:

Creating a PivotTable Report 162
PivotCaches 165
PivotTables Collection 165
PivotFields 166
CalculatedFields 170

我在 csv 输出中获取数据,例如:

Creating a PivotTable Report 162 PivotCaches 165 PivotTables Collection 165 PivotFields 166 CalculatedFields 170

【问题讨论】:

  • 这样做并运行但仍被写在一行中。
  • 你也应该关闭outfile,否则你可能会得到一个不完整的文件。或使用context managers
  • 什么是contentminimal reproducible example
  • @Shahin 我没有投反对票,但不清楚的是您的输入,而仍然不清楚的是您想要的输出。但无论是什么,解决方案现在都非常清楚了。您必须拆分您的行,但是您希望它们进入 CSV 文件(我猜是“文本,数字”),然后是 writerows(或 writerow 拆分后的每一行)。

标签: python python-3.x csv pypdf2


【解决方案1】:

对于这个特定的代码:

因为内容是项目列表[行]

contents = reader.getPage(7).extractText().split('\n')
for each in contents:
    writer.writerow(each)

print(contents)

试试这个并告诉我。

【讨论】:

  • 运行代码时,我在控制台中遇到的错误是:writer.writerow(content+"\n") TypeError: can only concatenate list (not "str") to list
  • 告诉我这是怎么回事
【解决方案2】:

假设你有

>>> print(s)
Line 1
Line 2
Line 3
Line 4

或该字符串的表示:

>>> s
'Line 1\nLine 2\nLine 3\nLine 4'

如果你按\n分割,则行尾不再存在:

>>> s.split('\n')
['Line 1', 'Line 2', 'Line 3', 'Line 4']

所以如果你将每一行依次打印到一个文件中,你会得到一行:

>>> with open('/tmp/file', 'w') as f:
...    for line in s.split('\n'):
...       f.write(line)
... 
# will write 'Line 1Line 2Line 3Line 4'

所以你需要在写入文件时添加行结尾:

writer.writerow('\n'.join(contents)) # assuming that is a list of strings

您还应该使用上下文管理器(我在上面使用的with)或关闭文件,否则您可能只会获得部分写入。

【讨论】:

    【解决方案3】:

    这是我所追求的解决方案:

    import csv
    from PyPDF2 import PdfFileReader
    
    outfile = open("conversion.csv",'w',newline='')
    writer = csv.writer(outfile)
    
    infile = open('some.pdf', 'rb')
    reader = PdfFileReader(infile)
    contents = reader.getPage(15).extractText().split('\n')
    for each in contents:
      writer.writerow(each.split('\n'))
    
    infile.close()
    outfile.close()
    

    由于 vintol 非常接近我正在寻找的输出,我将接受他的解决方案作为答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多