码迷,mamicode.com
首页 > 编程语言 > 详细

python CSV 文件的读写

时间:2018-04-06 23:47:31      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:文件   遍历目录   error   递归   with   切片   fresh   lin   line   

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 文件的读写

标签:文件   遍历目录   error   递归   with   切片   fresh   lin   line   

原文地址:https://www.cnblogs.com/pertinencec/p/8729135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!