Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I found the little python code to create the new csv file with selected columns from another csv file It is almost working correctly it just does not display each row on the new line. It is currently on the same line. Here is a code:

import csv

file_name =  'input.csv'

output_file = 'output.csv'

csv_file = open(file_name, 'r')

## note that the index of the year column is excluded

column_indices = [0,1,25,23,5,6,9,27,28,31,33,34,37,72,73,76,105,106,109,45,46,49]

with open(output_file, 'w') as fh:

    reader = csv.reader(csv_file, delimiter=',')

    for row in reader:

       tmp_row = []

       for col_inx in column_indices:

           tmp_row.append(row[col_inx])

       fh.write(','.join(tmp_row))

After the last column, I need it to create the new row whereas currently, everything is on the same row

1 Answer

0 votes
by (36.8k points)

Either use the csv.writer and use .writerow or write newline characters. One option is to use the print with the file= option:

# replace this

# fh.write(','.join(tmp_row))

# with this:

print(*tmp_row, sep=",", file=fh) # default is end="\n" so you get rows

Want to be a master in Data Science? Enroll in this Data Scientist

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...