Python - 从文本文件中读取逗号分隔值,然后将结果输出到文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21744804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Read comma separated values from a text file, then output result to text file
提问by user3304403
Basically I need to create a program that will add numbers read from a text file separated by commas. ie
基本上我需要创建一个程序来添加从逗号分隔的文本文件中读取的数字。IE
in
在
file.txt
文件.txt
1,2,3
4,5,6
7,8,9
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.
我不确定如何将文本文件中的每个数字分配给 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
但是我也不知道如何将结果输出到另一个文本文件。即答案.txt
6
15
24
6
15
24
Many thanks.
非常感谢。
回答by Joran Beasley
with open("file2.txt","w") as f:
print >> f,"\n".join(map(lambda x:str(sum(int(y) for y in x.split(","))),open("file1.txt")))
回答by jdhildeb
You can do this in fewer lines, but I hope you find this solution readable and easy to understand:
您可以用更少的行来完成此操作,但我希望您发现此解决方案可读且易于理解:
out = file('answers.txt', 'w')
for line in file('file.txt', 'r'):
s = 0
for num in line.strip().split(','):
s += int(num)
out.write("%d\n" % s)
回答by Sergii Dymchenko
For this task you may want to not work with files in your program directly, but work with standard input (input()or raw_input()in Python 2) and standard output (just print()).
对于此任务,您可能不希望直接处理程序中的文件,而是处理标准输入(input()或raw_input()Python 2)和标准输出(仅print())。
Then you specify input and output file names during invocation of your script:
然后在调用脚本期间指定输入和输出文件名:
python script.py < file.txt > answer.txt
With this scheme you can have a program like this (Python 2.7):
使用此方案,您可以拥有这样的程序(Python 2.7):
while (True):
try:
x, y, z = [int(val) for val in raw_input().split(',')]
print (x + y + z)
except EOFError:
pass
回答by Keshav Agrawal
Wondering if the file has only comma separated values then why not save file as ".csv" format. If you can then:
想知道文件是否只有逗号分隔值,那么为什么不将文件另存为“.csv”格式。如果可以的话:
You can always use a csv reader to read any CSV file as mentioned under the docs: http://docs.python.org/2/library/csv.html
您始终可以使用 csv 阅读器读取文档中提到的任何 CSV 文件:http: //docs.python.org/2/library/csv.html
Quick example for your scenario:
您的场景的快速示例:
with open('test.csv','rb') as csvfile:
csvreader = csv.reader(csvfile)
output_fil = open('output.txt', 'ab')
for row in csvreader:
result = 0
for elem in row:
result = result + int(elem)
print result
output_fil.writelines(str(result))
Where text.csv would contain input like:
其中 text.csv 将包含如下输入:
1,2,3
4,5,6
...
and output.txt shall contain:
和 output.txt 应包含:
6
15
..
回答by EducateMe
Welcome to StackOverflow!
欢迎使用 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".
在这里,我们打开了两个文件流“text.txt”和“answers.txt”。
Since we used "with", these filestreams will automatically close after the code that is whitespaced beneath them finishes running.
由于我们使用了“with”,这些文件流将在它们下方的空白代码完成运行后自动关闭。
Now, let's run through the file "text.txt" line by line.
现在,让我们逐行浏览文件“text.txt”。
for line in filestream:
This will run a for loop and end at the end of the file.
这将运行一个 for 循环并在文件末尾结束。
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".
现在,“currentline”包含“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!
我们必须将 int 函数包裹在“currentline”数组中的每个元素周围。否则,我们将连接字符串而不是添加整数!
Afterwards, we add the carriage return, "\n" in order to make "answers.txt" clearer to understand.
之后,我们添加回车符“\n”以使“answers.txt”更清晰易懂。
filestreamtwo.write(total)
Now, we are writing to the file "answers.txt"... That's it! You're done!
现在,我们正在写入文件“answers.txt”...就是这样!你完成了!
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)
回答by Hugh Bothwell
INFILE = "input.csv"
OUTFILE = "my.txt"
def row_sum(row, delim=","):
try:
return sum(int(i) for i in row.split(delim))
except ValueError:
return ""
with open(INFILE) as inf, open(OUTFILE, "w") as outf:
outf.write("\n".join(str(row_sum(row)) for row in inf))

