自己练习读取写入txt

读取文件中的内容生成一个list,然后修改list后再写会该文件
文件中的格式是:AA,BB,CC,DD

blist = []
for line in open('a.txt'):
blist.extend(line.split(','))
print(blist)
username = input(''请输入要插入的内容)
blist.append(username)
print(blist)
print(','.join(blist))
c = ','.join(blist)
f = open('a.txt', 'w')
f.writelines(c)
f.close()

如果只是一个人用文件的时候,open后不用close没有什么影响,但是多人都用到那个文件时,不close会影响其他人,改了下代码,读完了以后close,也运行成功了
blist = []
f = open('b.txt')
for line in f :
blist.extend(line.split(','))
print(blist)
f.close()
username = input('请输入要插入的内容:')
blist.append(username)
print(blist)
print(','.join(blist))
c = ','.join(blist)
f = open('b.txt', 'w')
f.writelines(c)
f.close()
 
posted @ 2016-11-08 10:43  xiaojinniu425  阅读(143)  评论(0编辑  收藏  举报