vicky113
vicky113

Reputation: 351

Reading and Writing data in CSV files in Python

I am new to Python and I am having some problems with CSV files in Python. Please help me out

  1. How do I open and read csv files in Python which are present in some other directory? I know we can do

    import csv 
    f = open('attendees1.csv')
    

    As long as my program file and csv file is in the same directory. But how do I provide a link to the csv file sitting in another directory?

  2. I have a list with multiple rows and columns, how do I transfer this data to a csv file and save it down in a particular location?

Please help me out

Upvotes: 1

Views: 2788

Answers (1)

mirosval
mirosval

Reputation: 6822

First argument of open() is file, which can be an absolute path like C:\Program Files\file.csv or a relative one like ../../file.csv here .. refers to the directory above the current directory and . refers to the current directory.

import csv
with open('../path/to/file.csv', 'w') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerows(your_row_data)

Where your_row_data is a list of lists.

Upvotes: 3

Related Questions