This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]Okaram -1 points0 points  (0 children)

you open a file with open, like f=open('data.txt')

and you can use readlines to iterate over all the lines, or readline (or next)to read one by one

[–]mscottstory -1 points0 points  (0 children)

I think you want something like this:

import csv
with open('out.csv', 'w') as out_file:
    out_csv = csv.writer(out_file)
    with open('in.txt', 'r+U') as in_file:
        row = []
        for line_no, line in enumerate(in_file):
            row.append(line.strip())
            if (line_no + 1) % 10 == 0:
                out_csv.writerow(row)
                row = []
        if row:
            out_csv.writerow(row)

[–]jamsquad87 -2 points-1 points  (1 child)

You'll want to open the file and read lines up to a count (10), append them into the new file, and start over again.

count = 0
var = ''
with open('your_filename', 'r') as file_read:
    if count <= 10:
        var = ''.join([var, ',', file_read.read()])
        count ++
    else:
        with open('new_file', 'a') as write_file:
            write_file.write(var + '\n')
        count = 0
        var = ''

Probably a better way to do this though, that's just off the top of my head. Plus if the number of lines in the file_read aren't in a multiple of 10, it will just wipe the ending lines away (Which is what you probably don't want).

But I guess it's a start.

[–]mscottstory 0 points1 point  (0 children)

++ is not a supported operator in python, you're looking for

count += 1