1

Problems: I am using python and CSV module to create multiple text files using rows from the CSV file. So that each row elements corresponds to one text files. Each text files are created such that ("text{}.txt".format(str(w[i])) it take value for w column and create files such as text2.txt, text3.txt, text7.txt, text8.txt, text10.txt text13.txt, text15.txt, and text16.txt.

Now the problem is that column w has repeated values for 10 and 15. So as I create text10.txt, text15.txt it will only write one line and skip to the next. I want to append all three rows(10 appearing in w column) in this text10.txt and all two rows( 15 appearing in w column) in text15.txt this is exceptional. But for all txt files it there will be the only a row written.

csv file look like this:

w, x, y, z

2 3 4 6

3 4 5 6

7 8 9 0

8 9 10 11

10 1 1 11

10 2 2 5

10 2 1 0

13 1 0 8

15 0 0 1

15 0 1 1

16 1 2 1

  1. Open CSV file, Skip header and read line/row
  2. write each row to text files such that text{} is index using values from column w
  3. ???????? append row
  4. output

Text files should look like this:

text2.txt:

2 3 4 6

text3.txt:

3 4 5 6

text7.txt:

7 8 9 0

text8.txt:

8 9 10 11

This text file has 3 rows append to next line

textt10.txt:

10 1 1 11

10 2 2 5

10 2 1 0

text13.txt:

13 1 0 8

This text file has 2 appended to the next line

text15.txt:

15 0 0 1

15 0 1 1

text16.txt:

16 1 2 1

Community
  • 1
  • 1
Ashish
  • 13
  • 3

2 Answers2

0

If you want to write, read and manipulate data, for instance concatenate data as you are asking, I would strongly recommend using the pandas library (Follow this 10 min tutorial to get started).

With pandas you can easily filter tables with simple criteria. For instance "select all rows that start with w=10". You can find an example of such a filtering procedure here.

Have fun with pandas!

Douasb'
  • 34
  • 3
  • I am looking for a solution, which helps me get those text files. This CSV file is just a sample – Ashish Jul 22 '19 at 19:14
0

When writing the file, open it in append mode, something like

with open(file_name, 'a'):
   write to csv.

Although, this would mean you'd have to write to a file for each row in your csv. This is slow and error prone. I would recommend grouping the rows before you write anything. Pandas, as mentioned in another answer is built for this kind of stuff, but you could also do it using something simple like a dictionary.

Fish11
  • 453
  • 3
  • 12