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