Scala:在文件中除最后一行之外的每行末尾添加值
我是斯卡拉的新手。有一个场景,我们需要在文件中除最后一行之外的每行末尾添加值。有一个用python编写的代码及其工作原理。我试图在scala中实现同样的功能,但没有成功。请帮忙Scala:在文件中除最后一行之外的每行末尾添加值,scala,apache-spark,scala-collections,Scala,Apache Spark,Scala Collections,我是斯卡拉的新手。有一个场景,我们需要在文件中除最后一行之外的每行末尾添加值。有一个用python编写的代码及其工作原理。我试图在scala中实现同样的功能,但没有成功。请帮忙 def create_ddl(): with open('C:\\Downloads\\output.csv', 'r') as istr: lines = istr.readlines() last = lines[-1] create=
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>
您有任何要粘贴的Scala代码吗?如果它不起作用也没关系,只要你告诉别人你在哪里,别人会更容易帮助你。这个片段看起来像Python。@AlexanderAzarov他在问如何将这个Python重写为Scala…@MateuszKubuszok啊,真的。我错过了那一点