Scala:在文件中除最后一行以外的每一行末尾添加值

Scala: Add value at the end of each row except the last row in a file

我是 Scala 新手。有一个场景,我们需要在文件中除最后一行之外的每一行的末尾添加值。在 python 中编写代码及其工作。我试图在 scala 中实现相同但没有成功。请帮忙。

def create_ddl():
    with open('C:\Downloads\output.csv', 'r') as istr:
            lines = istr.readlines()
            last = lines[-1]

            create='CREATE TABLE '+table_name+ ' ( '
            reformat="ROW FORMAT DELIMITED \n FIELDS TERMINATED BY ‘\t’ \n LINES TERMINATED BY ‘\n’;"
            with open('C:\Downloads\final_output_success.csv', 'w') as ostr:
                    print(create, file=ostr)
                    for line in lines:
                            if line is last:
                                    print(line, file=ostr)
                            else:
                                    line = line.rstrip('\n') + ','
                                    print(line, file=ostr)
                    print(')', file=ostr)
                    print(reformat, file=ostr)

看起来您正在尝试从文件中获取列名并在它们之间附加逗号以获取 "create table" 语法。您可以使用 mkString 函数执行此操作。

这是我在 windows 临时目录中的内容。

C:\Users\winos>type temp\cols.txt
col1
col2
col3
col4

C:\Users\winos>
C:\Users\winos>scala
Welcome to Scala version 2.11.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val x = scala.io.Source.fromFile("temp\cols.txt").getLines
x: Iterator[String] = non-empty iterator

scala> x.mkString(",")
res0: String = col1,col2,col3,col4

scala>

如果你有数组中的数据,它的工作方式相同

scala> val arr = Array("cola","colb","colc")
arr: Array[String] = Array(cola, colb, colc)

scala> arr.mkString("|")
res4: String = cola|colb|colc

scala>