python27 文件读写,,fileobject


fileobject = open(文件的绝对路径或相对路径,读写模式,其他可选参数)

‘‘‘r-读 文件不存在报错FileNotFoundError‘‘‘try:    f = open(‘file0.txt‘,‘r‘)    content = f.readlines()except FileNotFoundError:    content = Noneprint(content)

‘‘‘w-写 文件不存在创建;文件存在清除内容;重新写入‘‘‘f = open(‘file1.txt‘,‘w‘)f.write(‘first line111\nsecond line111‘)f.close()f = open(‘file1.txt‘,‘w‘)f.write(‘first line222\nsecond line222‘)f.close()f = open(‘file1.txt‘,‘r‘)print(f.read())print(f.readlines()) #到文档结尾了 空f.seek(0) #移到文档开头print(f.readlines()) #可以读取内容f.close()

‘‘‘a-追加 文件不存在报错;在最后追加内容‘‘‘f = open(‘file1.txt‘,‘a‘)f.write(‘\n #third line 222\n\n555‘) #追加f.close()f = open(‘file1.txt‘,‘r‘)print([ line.strip() for line in f.readlines()]) #去掉换行符f.close()

‘‘‘w+ r+ 读写。w+文件不存在创建;r+文件不存在报错。 同时可读写容易出错,需要移动指针。建议只读或只写‘‘‘f = open(‘file1.txt‘,‘r+‘)lines = f.readlines()lines[0] = ‘#第一行w+文件不存在创建;r+文件不存在报错。建议只读或只写w+ r+ 读写\n‘ # 与原第一行字数不同f.seek(0)f.writelines(lines)f.seek(0)print(f.readlines())  #第三行内容不对f = open(‘file1.txt‘,‘w+‘)f.writelines(lines)print(f.readlines()) #这样对了。f.close()

‘‘‘b 二进制‘‘‘f = open(‘file1.txt‘,‘rb‘)print(f.read())f.close()‘‘‘with使用完自动关闭‘‘‘with open(‘file1.txt‘,‘r‘) as f:    for line in f.readlines():        print(line.strip()) #去除换行符

‘‘‘显示文件的所有行 忽略以#开头的‘‘‘with open(‘file1.txt‘,‘r‘) as f:    for line in f.readlines():        if not line.startswith(‘#‘):            print(line.strip())
‘‘‘处理#前面的空格‘‘‘with open(‘file1.txt‘,‘r‘) as f:    lines = f.readlines()    for i in range(len(lines)):        if lines[i].strip().startswith(‘#‘) and (not lines[i].startswith(‘#‘)):            lines[i] = lines[i].strip()with open(‘file1.txt‘,‘w‘) as f:    f.writelines(lines)

‘‘‘显示文件的前N行‘‘‘N = 2file = ‘file1.txt‘with open(file,‘r‘) as f:    for i in range(N):        print(f.readline().strip())

‘‘‘显示文件总行数‘‘‘with open(file,‘r‘) as f:    print(‘总行数:‘,len(f.readlines()))

‘‘‘每次显示文件的2行‘‘‘file = input(‘filename‘)with open(file,‘r‘) as f:    lines = f.readlines()    f.seek(0)    pages = int(len(lines)/2 if len(lines)%2 == 0 else len(lines)/2+1) #总页数    page = 0 #页码    count = 0 #行数    if page < pages:        print(‘第%d页‘%(page+1))        for i in range(2):            if count < len(lines):                line = lines[count]                print(‘第%d行:%s‘%((count+1),line.strip()))                count += 1            else:                print(‘数据已显示完‘)                break        page += 1    while page < pages:        key = input(‘enter any key to continue...‘)        print(‘第%d页‘ % (page + 1))        for i in range(2):            if count < len(lines):                line = lines[count]                print(‘第%d行:%s‘ % ((count + 1), line.strip()))                count += 1            else:                print(‘数据已显示完‘)                break        page += 1

python27 文件读写

评论关闭