我是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)
答案 0 :(得分:1)
看起来您正在尝试从文件中获取列名,并在它们之间附加逗号以获取“创建表”语法。您可以使用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>