有没有办法使用ReadFromText转换(Python)读取Apache Beam中的多行csv文件?

时间:2018-04-19 05:07:40

标签: python google-cloud-platform google-cloud-dataflow apache-beam apache-beam-io

有没有办法在Python中使用ReadFromText转换读取多行csv文件?我有一个包含一行的文件,我试图让Apache Beam将输入读作一行,但无法让它工作。

def print_each_line(line):
    print line

path = './input/testfile.csv'
# Here are the contents of testfile.csv
# foo,bar,"blah blah
# more blah blah",baz

p = apache_beam.Pipeline()

(p
 | 'ReadFromFile' >> apache_beam.io.ReadFromText(path)
 | 'PrintEachLine' >> apache_beam.FlatMap(lambda line: print_each_line(line))
 )

# Here is the output:
# foo,bar,"blah blah
# more blah blah",baz

上面的代码将输入解析为两行,即使多行csv文件的标准是将多行元素包装在双引号内。

3 个答案:

答案 0 :(得分:1)

Beam不支持解析CSV文件。但是,您可以使用Python的csv.reader。这是一个例子:

import apache_beam
import csv

def print_each_line(line):
  print line

p = apache_beam.Pipeline()

(p 
 | apache_beam.Create(["test.csv"])
 | apache_beam.FlatMap(lambda filename:
     csv.reader(apache_beam.io.filesystems.FileSystems.open(filename)))
 | apache_beam.FlatMap(print_each_line))

p.run()

输出:

['foo', 'bar', 'blah blah\nmore blah blah', 'baz']

答案 1 :(得分:0)

ReadFromText将文本文件解析为换行符分隔的元素。所以ReadFromText将两行视为两个元素。如果您希望将文件的内容作为单个元素,则可以执行以下操作:

contents = []
contents.append(open(path).read()) 
p = apache_beam.Pipeline()
p | beam.Create(contents)

答案 2 :(得分:0)

没有一个答案对我有用,但这确实有用

(
  p
  | beam.Create(['data/test.csv'])
  | beam.FlatMap(lambda filename:
    csv.reader(io.TextIOWrapper(beam.io.filesystems.FileSystems.open(known_args.input)))
  | "Take only name" >> beam.Map(lambda x: x[0])
  | WriteToText(known_args.output)
)