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

1586010002-jmsa.png

Basically I need to create a program that will add numbers read from a text file separated by commas. ie

in

file.txt

1,2,3

4,5,6

7,8,9

So far I have the simple code

x = 1

y = 2

z = 3

sum=x+y+z

print(sum)

I'm not sure how I would assign each number in the text file to x,y,z.

What I would like is that it will iterate through each line in the text file, this would be with a simple loop.

However I also do not know how I would then output the results to another text file.

i.e. answers.txt

6

15

24

Many thanks.

解决方案

Welcome to StackOverflow!

You have the right idea going, let's start by opening some files.

with open("text.txt", "r") as filestream:

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

Here, we have opened two filestreams "text.txt" and "answers.txt".

Since we used "with", these filestreams will automatically close after the code that is whitespaced beneath them finishes running.

Now, let's run through the file "text.txt" line by line.

for line in filestream:

This will run a for loop and end at the end of the file.

Next, we need to change the input text into something we can work with, such as an array!

currentline = line.split(",")

Now, "currentline" contains all the integers listed in the first line of "text.txt".

Let's sum up these integers.

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

We had to wrap the int function around each element in the "currentline" array. Otherwise, instead of adding the integers, we would be concatenating strings!

Afterwards, we add the carriage return, "\n" in order to make "answers.txt" clearer to understand.

filestreamtwo.write(total)

Now, we are writing to the file "answers.txt"... That's it! You're done!

Here's the code again:

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值