I would like to take values from two csv files and put that in a single CSV file.
Please refer the Data in those two csv files:
CSV 1:
| | Status | P | F | B | IP | NI | NA | CO | U |
|---|----------|----|---|---|----|----|----|----|---|
| 0 | Sanity 1 | 14 | | | | | | 1 | |
| 1 | Sanity 2 | 13 | | 1 | | | | 1 | |
| | | | | | | | | | |
CSV 2:
| | Status | P | F | B | IP | NI | NA | CO | U |
|---|------------|-----|---|---|----|----|----|----|---|
| 0 | P0 Dry Run | 154 | 1 | | | 1 | | | 5 |
| | | | | | | | | | |
| | | | | | | | | | |
Code: I tried with following code:
filenames = glob.glob ("C:\\Users\\gomathis\\Downloads\\To csv\\*.csv")
wf = csv.writer(open("C:\\Users\\gomathis\\Downloads\\To
csv\\FinalTR.csv",'wb'))
for f in filenames:
rd = csv.writer(open(f,'r'))
next(rd)
for row in rd:
wf.writerow(row)
Actual result: While trying with above code, I didn't get the values from those above CSV files.
Expected result: I need that two files needs to be added in a single csv file and to be saved locally.
Modified code:
filenames = glob.glob ("C:\\Users\\gomathis\\Downloads\\To csv\\*.csv")
wf = csv.writer(open("C:\\Users\\gomathis\\Downloads\\To csv\\FinalTR.csv",'w'))
print(filenames)
for f in filenames:
rd = csv.reader(open(f,'r', newline=''))
next(rd)
for row in rd:
wf.writerow(row)
Latest result: I got the below result after modifying the code. And I didn't get the index like status P, F,B,etc. Please refer the latest result.
| 0 | P0 Dry Run - 15/02/18 | 154 | 1 | | | 1 | | | 5 |
|---|--------------------------------|-----|---|---|---|---|---|---|---|
| | | | | | | | | | |
| 0 | Sanity in FRA Prod - 15/02/18 | 14 | | | | | | 1 | |
| | | | | | | | | | |
| 1 | Sanity in SYD Gamma - 15/02/18 | 13 | | 1 | | | | 1 | |
open(f, 'rb'). If Python 3,open(f, 'r', newline=''). Writing follows the same pattern. The reason for this special handling for csv files is that the csv module needs to bypass Python's universal newline support.['C:\\Users\\gomathis\\Downloads\\To csv\\FinalTR.csv', 'C:\\Users\\gomathis\\Downloads\\To csv\\file1.csv', 'C:\\Users\\gomathis\\Downloads\\To csv\\file2.csv']FinalTR.csv? Anything? As @Ank points out you dord = csv.writer(open(f,'r'))when you should tord = csv.reader(open(f,'r')). You need acsv.readernot acsv.writerin that spot. Also, since your destination file exists in that list you should skip reading it.if f.endswith('FinalTR.csv'):continue