0

I have 2 files " CSV "

i want to insert the lines from the first file into the second file

how to insert specific numbers of lines like example the first 10 lines and also how to insert the all file

how to do this with python ?

for example :

First file include :

1 , A
2 , B
3 , C

Second file include :

4 , D

i want to add the lines from the first file to the second file so second file will be like this :

4 , D
1 , A
2 , B
3 , C

This is the code i use :

outfile = open("second.csv", "w", encoding="utf8")
for line in open("first.csv", "r", encoding="utf8"):
     outfile.write(line)
outfile.close()

But the problem in my code is not insert more lines the code delete what in second file and then insert into it what in the first file ( what i want is to insert lines without delete what was in the second file )

2
  • Hi, @MOHA7z, welcome to Stack Overflow. What have you tried so far? Commented Nov 18, 2019 at 22:11
  • @DaniilRyzhkov hello i add my code can you see if you can fix it thanks Commented Nov 18, 2019 at 22:30

2 Answers 2

0

See this post on reading CSV line by line:

Reading rows from a CSV file in Python

If you map the content to a pandas object, you can do this:

grid.to_csv('output.csv')
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. instead of using "w", use "a". "w" starts a file afresh, wiping out existing content. "a" appends to it
0

This is the solution

outfile = open("second.csv", "a", encoding="utf8")
for line in open("first.csv", "r", encoding="utf8"):
     outfile.write(line)
outfile.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.