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)