python csv file reading writting.

Reading and writing to a csv file is fairly simple using python.As python has both reader() and writter() method is  easy to use.In the code below,the script is reading a csv file and appending  row values in different list.the csv file had data in this format

name,link

nam,link

The code below take reads the csv file and take it name to a list and link to another list:

file_path = "path_of_your_csv_file"
shop = csv.reader(open(file_path, "rb"))
shop_list = []
shop_list.extend(shop)
file_name_list = []
rss_link_list = []
for d in shop_list:
file_name_list.append(d[0])
rss_link_list.append(d[1])

And the writing to a csv file was interesting,I tried to write in a csv file and each time when a write was writting data but when a new write operation was executed previous data was erased.Actually,I was missing silly point the I didnt mention the data should be appended when writted.The code was as belows:

def csv_writer(data_list,file_path):
    import csv
    file_p = open(file_path, "wb")
    write_pattern = csv.writer(file_p, delimiter=",", quotechar=",")
    write_pattern.writerow(data_list)
    file_p.close()

In this method user have to pass data and the file path where the csv file will exists should be declared.

You can find more about python csv read write form here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s