文件的操作是非常常用的。下面通过基本的例子了解对一般的TXT文档的操作。
1.创建一个TXT文本,在其中写入学生的基本信息。包括:姓名,性别,地址4个信息。
代码:
11 #!/usr/bin/env python
10 # encoding: utf-8
9
8 f=open('filecreat.txt','w')
7 f.write('name'+'\tsex'+'\tcellphone'+'\t\taddress'+'\n')
6 flag=1
5 while flag==1:
4 name=raw_input('please input a name:')
3 sex=raw_input('please input the sex:')
2 cellphone=raw_input('please input the cellphone number:')
1 address=raw_input('please input the address:')
12 s=name+'\t'+sex+'\t'+cellphone+'\t\t'+address+'\n'
1 f.write(s)
2 flag=input('will you go on?(1/0):')
3 f.close()
结果:
please input a name:iker
please input the sex:manplease input the cellphone number:123456789
please input the address:XMU
will you go on?(1/0):1
please input a name:456123
please input the sex:UESTC
please input the cellphone number:1234567894
please input the address:xsf
will you go on?(1/0):0
ikerpeng@~/text/mlexcersise$ python excersice2.py
name sex cellphone address
iker man 123456789 XMU
456123 UESTC1234567894xsf