Python入门篇之文件

2019-10-05 16:04:31王旭

示例

1.文件的打开或创建


#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

filehandler = open('test.txt','w')               #以写模式打开文件,如果文件不存在则创建
filehandler.write('this is a file open/create test.nthe second line.')

filehandler.close()
#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

filehandler = open('test.txt','a')      #以追加模式打开文件,如果文件不存在则创建

filehandler.write('nappend the text in another line.n')

filehandler.close()

2.读取文件


#!/usr/bin/env python
#-*- encoding:UTF-8 -*-

filehandler = open('test.txt','r')    #以读方式打开文件,rb为二进制方式(如图片或可执行文件等)
 
print 'read() function:'              #读取整个文件
print filehandler.read()
 
print 'readline() function:'          #返回文件头,读取一行
filehandler.seek(0)
print filehandler.readline()
 
print 'readlines() function:'         #返回文件头,返回所有行的列表
filehandler.seek(0)
print filehandler.readlines()
 
print 'list all lines'                #返回文件头,显示所有行
filehandler.seek(0)
textlist = filehandler.readlines()
for line in textlist:
      print line

print 'seek() function'               #移位到第32个字符,从33个字符开始显示余下内容
filehandler.seek(32)
print filehandler.read()

print 'tell() function'               #移位到文件头,从头开始显示2位字符
filehandler.seek(0)
print filehandler.readline()          #显示第一行内容
print filehandler.tell()              #显示当前位置
print filehandler.readline()          #显示第二行内容
print filehandler.read()              #显示余下所有内容

filehandler.close()                   #关闭文件句柄

3.文件系统操作


#!/usr/bin/env python
#-*- encoding:utf-8 -*-

import os,fnmatch,glob

for fileName in os.listdir ( '/root' ):                 #列出/root目录内容,不包括.和..