#Open your file
try:
#Write data to your file
finally:
file.close()
#使用write()写文件
file_obj=open('test.txt','w')
str1='hello\n'
str2='world\n'
str3='python'
file_obj.write(str1)
file_obj.write(str2)
file_obj.write(str3)
file_obj.close()
#使用writelines()写文件
file_obj=open('test.txt','w')
str1='hello\n'
str2='world\n'
str3='python'
file_obj.writelines([str1,str2,str3])
file_obj.close()
#输出 本地test.txt文件
hello
word
python
#使用read
print 'Use the read'
file_obj=open('test.txt','r')
s=file_obj.read()
print s
file_obj.close
#使用readline
print 'Use the readline'
file_obj=open('test.txt','r')
line1=file_obj.readline()
line1=line1.rstrip('\n')
print 'l1 ',line1
line2=file_obj.readline()
line2=line2.rstrip('\n')
print 'l2 ',line2
line3=file_obj.readline()
line3=line3.rstrip('\n')
print 'l3 ',line3
file_obj.close
#使用readlines
print 'Use the readlines'
file_obj=open('test.txt','r')
li=file_obj.readlines()
print li
file_obj.close
Use the read hello world python Use the readline l1 hello l2 world l3 python Use the readlines ['hello\n', 'world\n', 'python']
#格式化写入
fd=open('format.txt','w')
head="%-8s%-10s%-10s\n"%('Id','Name','Record')
fd.write(head)
item1="%-8d%-10s%-10.2f\n"%(10001,'Eastmount',78.9)
fd.write(item1)
item2="%-8d%-10s%-10.2f\n"%(10002,'CSDN',89.1234)
fd.write(item2)
fd.close()
#输出
Id Name Record
10001 Eastmount 78.90
10002 CSDN 89.12
#使用while循环
fr=open('test.txt','r')
str=fr.readline()
str=str.rstrip('\n')
while str!="":
print str
str=fr.readline()
str=str.rstrip('\n')
else:
print 'End While'
fr.close
#使用for循环
rfile=open('test.txt','r')
for s in rfile:
s=s.rstrip('\n')
print s
print 'End for'
rfile.close()
s='www.csdn.NET' si=iter(s) #生成迭代器 print si.next() #调用next依次获取元素,最后迭代器没有返回值时引发StopIteration异常
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有