Read and write Python CSV file

Source: Internet
Author: User

1.CSV file
ImportCsvwith Open (R"E:\code\0_DataSet\tianchi_2015_mobile_recommand\fresh_comp_offline\tianchi_fresh_comp_train_user.csv","r+") as Rdfile, open ("Data.csv","w+", newline="") as Wrfile:#WriteFile must open with newline+= "" or blank line would appear        #1 Create reader & writerCsvreader =Csv.reader (rdfile) Csvwriter=Csv.writer (wrfile)#2 Get the Headmost 10000 line and write to Wrfile         forLine,iinchZip (Csvreader,range (10001): Csvwriter.writerow (line)

CSV file Read and write:

 ①open ()

The write must be newline= with the specified parameter ""

② Create reader () | Writer ()

Csv.reader ()

Csv.writer ()

③ Reading and writing

Without ReadLine read directly using the for line in Csvreader

Write using Csv.writer.writerow ()

2. Implementation of Str.replace ()

1) str.split () +str.jion (sequence)

1 def Mystrreplace (SRC,OLDSTR,NEWSTR): 2     return newstr.join (Src.split (OLDSTR))

2) Slicing + recursion

def Mystrreplace (SRC,OLDSTR,NEWSTR):     = Src.find (oldstr)    if pos = =-1        := src[:    ]else:         = src[:p os]+newstr+src[pos+len (oldstr):]        = mystrreplace (target,oldstr,newstr)     return Target

3. Python traverses the directory and prints the. PYc End of the file

1  fromOsImportWalk2  forRoot,dir,filesinchWalk"."):3     " "4 root,dir,files = Os.walk (top[, topdown=true[, onerror=none[, Followlinks=false]])5     " "6      forFileinchFiles:7         ifFile.endswith (". PYc"):8             Print(file)

Read and write Python CSV file

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.