您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> 编程语言综合 >> 正文

Python文件操作类操作实例代码

作者:佚名    责任编辑:admin    更新时间:2022-06-22

  #!/usr/bin/env python

01 #!/usr/bin/env python 

02 #coding:utf-8 

03 # Author: 酷酷

04 # Purpose: 文件操作类 

05 # Created: 2011/1/1 

06 

07 #声明一个字符串文本 

08 poem=''' 

09 Programming is fun测试 

10 When the work is done 

11 if you wanna make your work also fun: 

12 use Python! 

13 ''' 

14 #创建一个file类的实例,模式可以为:只读模式('r')、写模式('w')、追加模式('a') 

15 f=file('poem.txt','a') #open for 'w'riting 

16 f.write(poem) #写入文本到文件 write text to file 

17 f.close() #关闭文件 close the file 

18 

19 #默认是只读模式 

20 f=file('poem.txt') 

21 # if no mode is specified,'r'ead mode is assumed by default 

22 while True: 

23 line=f.readline() #读取文件的每一个行 

24 if len(line)==0: # Zero length indicates EOF 

25 break 

26 print line, #输出该行 

27 #注意,因为从文件读到的内容已经以换行符结尾,所以我们在输出的语句上使用逗号来消除自动换行。 

28 

29 #Notice comma to avoid automatic newline added by Python 

30 f.close() #close the file 

31 

32 #帮助 

33 help(file)