0

What I'm trying to do is basically reading a csv file to a list, ( one column only ). Then I need to read 11 elements ( one element = 9 digit number ) from the list, with comma, to a row with newline. All goes into another text file. 11 elements i a row match a A4 sheet. Then iterate over remaining elements in the list. I can't figure out how. Below follows my code I'm working on:

count = 0

textfile = 'texstf.txt'
filepath = 'testfile2.csv'

with open(filepath, "r") as f:
    lines = [ str(line.rstrip()) for line in f ]
    for key in lines:
        while(count < 11):
            with open(textfile, "w") as myfile:
                myfile.write(','.join(lines))
                count += 1

csv sample:

6381473
6381783
6381814

...
expected output to file sample:

6381473,6381783,6381814   


lunar75
  • 1
  • 1

1 Answers1

1

I ran your code and it looks like it is working. If you could provide any more context of what specifically is not working with your code such as error messages, that would be helpful. Make sure you have the correct filepath for each file you are trying to read and write.

Here is an alternative way to do this based off of this similar question:

import csv
import os

textfile = os.getcwd() + r'\texstf.txt'
filepath = os.getcwd() + r'\testfile2.csv'

with open(textfile, "w") as my_output_file:
    with open(filepath, "r") as my_input_file:
        [ my_output_file.write(" ".join(row)+',') for row in csv.reader(my_input_file)]
    my_output_file.close()
  • I have like a 350 elements in the list and I end up having all elements in one singe row or line comma separated when writing to new file. I need to have only 11 elements in a row, to mach a A4 sheet in width. Thanks for your response NoStorm1403 – lunar75 Jul 18 '22 at 16:18
  • After looking around and reading I have an almost working code. The print statement outputs exactly what I'm looking for. The only thing which doesn't work is writing the same results to a file. I would like to post my solution but then I will have to post a Answer Your Question again. Would it be ok? – lunar75 Jul 18 '22 at 18:09
  • Yes, you can post the question again and I can see if I can help get it into the file in the format you are looking for – NoStorm1403 Jul 19 '22 at 18:49