1. 程式人生 > >python CSV 文件的讀寫

python CSV 文件的讀寫

+= RR 打印 src rec nbsp reader blank als

1.CSV文件

import csv

with 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 will appear
        #1 create reader & writer
csvReader = csv.reader(rdFile) csvWriter = csv.writer(wrFile) #2 get the headmost 10000 line and write into wrFile for line,i in zip(csvReader,range(10001)): csvWriter.writerow(line)

CSV 文件的讀寫:

  ① open()

    寫入必須用 指定參數 newline=""

  ②創建 reader() | writer()

    csv.reader()

    csv.writer()

  ③讀寫

    不用 readline讀 直接使用 for line in csvReader讀

    使用 csv.writer.writerow()寫入

2. str.replace()的實現

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

1 def myStrReplace(src,oldStr,newStr):
2     return newStr.join(src.split(oldStr))

  2)切片+遞歸

def myStrReplace(src,oldStr,newStr):
    pos 
= src.find(oldStr) if pos == -1: target = src[:] else: target = src[:pos]+newStr+src[pos+len(oldStr):] target = myStrReplace(target,oldStr,newStr) return target

3. python遍歷目錄,並打印.pyc 結尾的文件

1 from os import walk
2 for root,dir,files in walk("."):
3     ‘‘‘
4         root,dir,files = os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
5     ‘‘‘
6     for file in files:
7         if file.endswith(".pyc"):
8             print(file)

python CSV 文件的讀寫