1

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

JRodDynamite
  • 12,325
  • 5
  • 43
  • 63
vicky113
  • 351
  • 1
  • 6
  • 19
  • 1
    You can specify the whole path in the open statement. E.g.: f = open('C:\\mypath\\myfile.csv') or f = open('..\\other_path\\myfile.csv') if you are on Windows. – kotlet schabowy Jan 05 '16 at 06:05
  • Thanks Kotlet, Can you help me with the 2nd query as well? – vicky113 Jan 05 '16 at 06:07
  • 1
    you can transfer your data with the csv.writer . Please see: https://docs.python.org/2/library/csv.html – kotlet schabowy Jan 05 '16 at 06:07
  • 1
    It would help to know the version of Python (2 vs. 3) and whether you need to handle non-ASCII input/output. The `csv` module is quirky, and requires the original file to be opened in different ways on Py2 vs. Py3. Use the `csv` docs appropriate to your Python version (kotlet gave the link for Py2, and the [Py3 `csv` docs are here](https://docs.python.org/3/library/csv.html)). – ShadowRanger Jan 05 '16 at 07:33
  • Possible duplicate of [How do I read and write CSV files with Python?](http://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – Martin Thoma Jan 11 '17 at 07:56

1 Answers1

3

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.

mirosval
  • 6,671
  • 3
  • 32
  • 46