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

Run windows command line command using python

I was just playing with my python interpreter in my windows 7 system today and thinking what to do silly,fun.

Then just searched for the library in python which can be used to list windows directory/file.

The OS module is used in this case and it was simple.I put the windows command that I want to execute and passed it inside popen() .


windows = "dir"
command = os.popen(windows).read()
print command

Its simple 🙂

If any one have better solution than this please drop a line,that I can know that.

To know details about python’s OS module,click here.