玩蛇网提供最新Python编程技术信息以及Python资源下载!

在CSV文件中添加联系人的python方法

python 培训

学习Python有一段时间了,想自己动手写点什么,想到了一个比较简单的,就是在CSV文件中增加联系人的这个操作。

在CSV文件中添加联系人的python方法

import sys
import os
import time
import csv

def addPerson(filename):
	'''Add a new Person\'s Tel'''
	person = raw_input('Enter the person\'s name: ')
	tel = raw_input('Enter the person\'s tel: ')
	update=time.strftime('%Y-%m-%d %H:%m:%S')
	
	f=csv.writer(file(filename, 'a'))
	f.writerow([person,tel,update])
	#f.close()
	
	print 'New Person\'s tel has been added!'
	
if (os.path.isfile('TelBook.csv'))==False:
		title=['NAME','TEL','TIME']
		f=csv.writer(file('TelBook.csv','w'))
		f.writerow(title)
		#f.close()
		
input=raw_input('Do you wanna Enter a new Person\' tel?(y/n)')

if input=='y':
	flag=True

else:
	flag=False
	print 'Thanks, Bye!'

while flag:		
	addPerson('TelBook.csv')
	t=raw_input('Do you wanna Enter another?(y/n)')
	if t!='y':
		print 'Thanks, Bye!'
		break
#www.iplaypython.com

这部分是修改了csv文件中多一空行的问题

import sys
import os
import time
import csv

def addPerson(filename):
	'''Add a new Person\'s Tel'''
	person = raw_input('Enter the person\'s name: ')
	tel = raw_input('Enter the person\'s tel: ')
	update=time.strftime('%Y-%m-%d %H:%m:%S')
	
	f=csv.writer(file(filename, 'ab'))
	record=[person,tel,update]
	f.writerow(record)
	#f.close()
	
	print 'New Person\'s tel has been added!'
	
if (os.path.isfile(r'D:\Exercise\Python\TelBook\TelBook.csv'))==False:
		title=['NAME','TEL','TIME']
		#f=csv.writer(file(r'D:\Exercise\Python\TelBook\TelBook.csv','w'))
		f=csv.writer(file(r'D:\Exercise\Python\TelBook\TelBook.csv','wb'))
		f.writerow(title)
		file(r'D:\Exercise\Python\TelBook\TelBook.csv').close()


input=raw_input('Do you wanna Enter a new Person\' tel?(y/n)')
if input=='y':
	flag=True
else:
	flag=False
	print 'Thanks, Bye!'
while flag:		
	addPerson(r'D:\Exercise\Python\TelBook\TelBook.csv')
	t=raw_input('Do you wanna Enter another?(y/n)')
	if t!='y':
		print 'Thanks, Bye!'
		break
	file(r'D:\Exercise\Python\TelBook\TelBook.csv').close()

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/other/o2332.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-04-21 09:38 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部