如何在末尾添加一行到txt文件以进行计算?

时间:2019-05-13 18:20:55

标签: python r sql-server

我有一个从SSIS生成的文本文件,数据来自SQL Server数据库。文本文件中没有列标题。在文本文件中,我需要查看是否有一种方法可以仅在第一列的最底部添加一行来进行一些计算(计数和总和)。

例如,当前文本文件如下:

111 Test Street         Texas                John Doe         20.00
123 Test Street         Alabama              John Doe         30.00

我正在寻找是否可以让它看起来像这样,它可以计算总记录并添加最后一列:

111 Test Street         Texas                John Doe         20.00
123 Test Street         Alabama              John Doe         30.00
Users: 2   Amount: 50.00

2 个答案:

答案 0 :(得分:1)

我能够使用它,我首先需要使用write.fwf,因为我的文本文件需要具有固定的宽度,所以我做到了:

write.fwf(data, file = "test.txt", width = c(57,19,2), colnames = FALSE)

然后我用了:

write(paste0("Users:   ", nrow(data),"   Total:    ", sum(data1$amount)), file = "test.txt", append = TRUE)

我想将其发布以供参考,以防万一有人偶然发现这种情况。

再次感谢Shree!

答案 1 :(得分:0)

这是在R中使用iris作为虚拟数据示例的一种简单方法。让我知道这是否满足您的需求-

# read your data into a dataframe
df <- iris[1:2, ]
# create this file in your working directory
sink(file = "test.txt", type = "output")
# add dataframe as is to text file
df
# add summary line to data frame
cat(
  paste0("Users: ", unique(df$Species), "     Total: ", sum(df$Sepal.Length)),
  file = 'test.txt', append = T, sep = '\n'
  )
# close connection to text file
sink()

# output text file -

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
Users: setosa     Total: 10