1

i need to export specific column from csv to new csv, but i couldn't get proper result.plase support to chcek

Id Name Course City Session

21 Mark Python London Morning

22 John Python Tokyo Evening

32 Shaun Java Tokyo Morning

import csv
with open(r'D:\Clouds\OneDrive\Desktop\python_tamrin\students.csv', 'r') as read_obj:
    csv_reader = csv.reader(read_obj)
    with open ('new_nemes_1.csv','w', newline='') as new_file:
        csv_writer=csv.writer(new_file)
        for line in csv_reader:
            c_1 =row['Id']
            csv_writer.writerow('c_1') 
nasrin
  • 15
  • 5

1 Answers1

1

line (or row) is a list, it doesn't have Id key. You need to write a slice of that list to the new file

...
for row in csv_reader:
    csv_writer.writerow(row[:1])
Guy
  • 46,488
  • 10
  • 44
  • 88
  • thanks alot, it worked , if i want to have specific Id from row[:1], for example 22, how i should modify ? – nasrin Mar 27 '23 at 07:42
  • @nasrin add a condition to the `for`, `if row[0] == '22':` – Guy Mar 27 '23 at 07:45
  • if i have multiple CSV files with same data structure in one folder , how i can loop this activity to get the data of all CSVs of that folder? sorry for many questions, – nasrin Mar 27 '23 at 09:06
  • 1
    @nasrin something like that https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory – Guy Mar 27 '23 at 09:11
  • @nasrin If you have a new question you should post a new question, it's difficult to answer in the comments. – Guy Mar 27 '23 at 09:12
  • thank u and i will make new post in such these cases in future – nasrin Mar 27 '23 at 11:05