Python - Read comma separated values from a text f

2020-06-24 05:49发布

问题:

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.

回答1:

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)


回答2:

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)


回答3:

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()).

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):

while (True):
    try:
        x, y, z = [int(val) for val in raw_input().split(',')]
        print (x + y + z)
    except EOFError:
        pass


回答4:

Wondering if the file has only comma separated values then why not save file as ".csv" format. If you can then:

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

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:

1,2,3
4,5,6
...

and output.txt shall contain:

6
15
..


回答5:

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))


回答6:

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")))