0

a.csv

number  address 
------  ------- 
1
2
3
4 
5

b.csv

number    address1  address2
------    --------  --------
2          abc      def
3          abc1     def1
4          abc2     def2

Numbers 2 , 3 and 4 found in both a and b.csv. So I want the final output in the a.csv file itself like below:

number    address 
------    -------
1
2         abc def
3         abc1 def1
4         abc2 def2
5

Code I tried:

nos = []
with open("a.csv", "r") as# Skip the first line
  f.readline()
  for line in f:
  nos.append(int(line.strip("\n")))

with open("b.csv", "r") as f:

  f.readline()
  for line in f:
    if int(line.split(",")[1]) in nos:

How to write into a.csv file itself back?

martineau
  • 119,623
  • 25
  • 170
  • 301
Rev
  • 1
  • 3
  • Does this answer your question? [Python write to CSV line by line](https://stackoverflow.com/questions/37289951/python-write-to-csv-line-by-line) – tibi Dec 15 '20 at 22:24

1 Answers1

0

To write a csv file you can use the csv library:

import csv

...
with open('c.csv', mode='w') as new_file:
    writer = csv.writer(new_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(line.split(','))

EDIT:

with open('b.csv', 'r') as b, open('c.csv', 'w') as c:
    b = b.readline()
    writer = csv.writer(c, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for line in b:
        if int(line.split(',')[1]) in nos:
            writer.writerow(line.split(','))

see this answer

EDIT:

As shown in the top answer, you actually already have line of csv in your line variable. You could therefore just do this:

with open('b.csv', 'r') as b, open('c.csv', 'w') as c:
    b = b.readline()
    for line in b:
        if int(line.split(',')[1]) in nos:
            c.write(line)
            c.write('\n')
nihilok
  • 1,325
  • 8
  • 12
  • maybe better to put the for loop inside the second `with open()` – nihilok Dec 15 '20 at 22:39
  • You mean like below: – Rev Dec 15 '20 at 22:42
  • with open("b.csv", "r") as f: f.readline() for line in f:, mode='w') as new_file: if int(line.split(",")[1]) in nos: with open('a.csv' mode='w') as new_file: like this ? – Rev Dec 15 '20 at 22:43
  • Thank you! Will it write the whole row values from b.csv to c.scv ? As b.csv have more than 1 column. I need the whole row values from b.csv to c.csv. – Rev Dec 15 '20 at 22:55
  • I ended up having below error with the above code while writing into a new line. c.write(line) TypeError: a bytes-like object is required, not 'str' – Rev Dec 16 '20 at 02:15
  • Sorry changed the wb to a w – nihilok Dec 17 '20 at 09:49