How to handle CSV file using Python

Source: Internet
Author: User

As I need to the read something from a CSV file using Python. I got something and put it here.

Module:csv

Import CSV

File_full_path = ' D:\\work\\script\\my script\\book1.csv '

def f ():
With open (File_full_path, ' RB ') as CSVFile:
For row in Csv.reader (CSVFile, delimiter= ", quotechar= ' | '):
Print type (ROW)
For Eachcol in row:
Print Eachco

if __name__ = = ' __main__ ':
F ()

OUTPUT:

C:\Python27\python.exe "D:/work/script/my script/my-test.py"
<type ' list ' > #here we know each row is read as a list
Col11,col12,col12,,cole #The col which is empty was stored as a empty in the list
<type ' list ' >
Col21,col22,col23,,

Process finished with exit code 0

How to write to CSV file

Def f_w ():
Datas = [] #using list to store data
With open (Config_file_path, ' R ') as F: #read data from a txt FILE
First = True
For line in F:
If first:
Datas.append (Re.findall (' [a-za-z]+ '), line) #find Word and Retuan a list
First = False
Else
Datas.append (Re.findall (' [A-za-z_ 0-9]+ ', line)] #as the data has _and 0-9
For data in Datas:
Print Data,len (data)
With open (File_full_path, ' WB ') as CSVFile: #open the FILE need to using B mode
Csvwriter = Csv.writer (csvfile) #converte to Csvwriter
For data in Datas: #for each line in the list write to CSV
Csvwriter.writerow (data)

How to handle CSV file using Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.