python输入逗号分隔值文件_Python-从文本文件中读取逗号分隔的值,然后将结果输出到文本fi...

欢迎来到StackOverflow!

你的想法是对的,让我们先打开一些文件。with open("text.txt", "r") as filestream:

with open("answers.txt", "w") as filestreamtwo:

在这里,我们打开了两个文件流“text.txt”和“answers.txt”。

由于我们使用了“with”,这些文件流将在下面空白的代码运行完后自动关闭。

现在,让我们逐行运行文件“text.txt”。for line in filestream:

这将运行for循环并在文件末尾结束。

接下来,我们需要将输入文本更改为可以使用的内容,例如数组!currentline = line.split(",")

现在,“currentline”包含“text.txt”第一行中列出的所有整数。

让我们把这些整数加起来。total = str(int(currentline[0]) + int(currentline[1]) + int(currentline [2])) + "\n"

我们必须在“currentline”数组中的每个元素周围包装int函数。否则,我们将连接字符串,而不是添加整数!

之后,我们添加回车“\n”,以便更清楚地理解“answers.txt”。filestreamtwo.write(total)

现在,我们正在写入文件“answers.txt”。。。就这样!你完了!

下面是代码:with open("test.txt", "r") as filestream:

with open("answers.txt", "w") as filestreamtwo:

for line in filestream:

currentline = line.split(",")

total = str(int(currentline[0]) + int(currentline[1]) + int(currentline [2])) + "\n"

filestreamtwo.write(total)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值