Python----文件操作

来源:互联网 发布:mac如何下载dota2 编辑:程序博客网 时间:2024/06/08 19:38

文件操作基本动作包括:
1.找到一个文件并打开,找到文件句柄,并赋给一个变量值。
2.通过句柄对文件进行操作。
3.关闭文件。

打开文件:

# !/usr/bin/env python# -*- coding: utf-8 -*-# Author: Justin Chan'''open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):    'r'       open for reading (default)    'w'       open for writing, truncating the file first    'x'       create a new file and open it for writing    'a'       open for writing, appending to the end of the file if it exists    'b'       binary mode    't'       text mode (default)    '+'       open a disk file for updating (reading and writing)    'U'       universal newline mode (deprecated)文件打开模式:1.r只读模式:r(默认)2.r+可读可写。注意:在Python3.x中,如果是r+模式,不管写之前是否有调用readline()使指针隐式位移,在第一次调用write()函数时,指针都位于文件的末尾,内容也是写到文件末尾。除非在write()之前,调用seek()使指针显式位移到指定追加内容的位置。

f = open(“yesterday”,”r+”)
print(f.readline())
print(f.readline())
print(f.readline())
f.write(“%%%%%%%”)
print(f.tell())
print(f.tell())
f.seek(10)
print(f.tell())
f.write(“lllll”)
print(f.tell())
f.write(“**===”)
print(f.tell())
f.closed()

3.w写模式:w这里需要特别注意w,w模式会**覆盖**原文件的内容。4.w+写读模式,可以打开写,然后读。写读模式条件下,会向清空之前文件的内容,然后往文件里面写数据。5.a追加,在原文件尾部追加内容。6.a+追加写读,追加后读文件。7.rb,wb,ab以二进制文件的格式打开文件,这样打开的文件的格式都是字节格式。什么时候用二进制格式打开?在跨平台或者影音文件时,最好以二进制格式打开。二进制模式不能带编码参数encoding="utf-8"

f = open(“yesterday”,”rb”)
print(f.readline())
b’hhhhhhhhhhhhhhh\n’ #二进制输出开头有带b字母标志,表示按字节输出。

8.x'''f_yes = open("yesterday",'r',encoding="utf-8")#f_yes文件句柄,即文件的内存对象,文件在内存的起始地址。#打开文件时要注意编码问题,有两种方法,一种是open函数带编码类型的参数入uhf-8#另一种是在代码开头添加编码格式# -*- coding: utf-8 -*-data = f_yes.read()#第一遍读取文件data2 = f_yes.read()#第二次操作句柄读取文件print(data)#正常输出文件全部内容print("---------------data2------------")print(data2)#没有打印输出data3 = f_yes.readline()print(data3)#readline()按行读取,且只读取一行data4 = f_yes.readlines()print(data4)#readlines()按行读取,且读取多行f_yes = open("yesterday",'r',encoding="utf-8")print(f_yes.readlines())#输出的是一个列表,每行内容为一个列表元素。for line in f_yes.readlines():    print(line)for line in f_yes.readlines():    print(line.strip())#line.strip()去掉每行的分隔符和换行符,去掉多余的行。

在print(data2)时需要注意,文件句柄的操作类似于指针,当读取一遍文件后,指针后移到文件的最后位置,此时,再打开文件当然是没有内容的。

读取文件全部内容方法:

  1. 屌丝方法
 for index,lines in enumerate(f_yes.readlines()):    if index == 9:        print("-------我是分隔线-----")        continue    print(lines.strip())#循环读取文件,读取出索引值,注意读取索引值方法for index,lines in enumerate()

这种使用readlines()的方法是把文件的全部内容一次性读取,封装成一个列表,并存储到内存中。
当文件非常大时,会出现内存被占满的情况。非常低效。
2. 土豪方法

count = 0for line in f_yes:    if count == 9:        print("-------我是分隔线-----")        count += 1        continue    print(line.strip())    count +=1

使用for line in f_yes:每次只读取一行数据到内存中,后一次读取的内容覆盖前一次读取的内容,高效的方法。
此外,python自增不支持++运算符,所以要使用count += 1

按要求读取固定长度字符

f.read()#不带参数的read()表示一次读取句柄f所指向的文件的全部内容。f.read(n)#read(n)可以接收参数n,表示读取句柄f所指向的后面n个字符数据。f.tell()#输出句柄f所指向的字符位置(以字符计数),文件起始位置为0。f.seek(n)#把文件句柄f重新指向第n个字符位置。print(f.encoding)#打印文件的字符编码,比如UTF-8print(f.fileno())#返回系统中打开的IO文件编号。print(f.name)#打印文件名。print(f.isatty())#判断文件是否一个tty设备。print(f.seekable())#判断文件是否可以seek到任意位置,比如是终端设备文件就不能向普通文本文件一样seek。print(f.readable())#判断文件是否为可读文件。print(f.flush())#实时刷新,内存和硬盘的数据可能存在时间延迟。在内核中,内存和硬盘是速率不一样,内存会按照一定大小和时间刷新到硬盘中。f.truncate(n)#文件头开始截断n个字节,n字节之前的内容还在,n字节之后内容被清空。

刷新进度条实例

import sys,timefor num in range(20):    sys.stdout.write("#")    sys.stdout.flush()    time.sleep(0.1)
原创粉丝点击