文件操作

1.1 对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件

现有文件如下:

   昨夜寒蛩不住鸣。
  惊回千里梦,已三更。
  起来独自绕阶行。
  人悄悄,帘外月胧明。
  白首为功名,旧山松竹老,阻归程。
  欲将心事付瑶琴。
  知音少,弦断有谁听。
f = open('小重山') #打开文件
data=f.read()#获取文件内容
f.close() #关闭文件

注意 if in the win,hello文件是utf8保存的,打开文件时open函数是通过操作系统打开的文件,而win操作系统

默认的是gbk编码,所以直接打开会乱码,需要f=open('hello',encoding='utf8'),hello文件如果是gbk保存的,则直接打开即可。

1.2 文件打开模式  

========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'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)
========= ===============================================================

先介绍三种最基本的模式:

# f = open('小重山2','w') #打开文件
# f = open('小重山2','a') #打开文件
# f.write('莫等闲1\n')
# f.write('白了少年头2\n')
# f.write('空悲切!3')

1.3 文件具体操作

def read(self, size=-1): # known case of _io.FileIO.read
"""
注意,不一定能全读回来
Read at most size bytes, returned as bytes. Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""
return "" def readline(self, *args, **kwargs):
pass def readlines(self, *args, **kwargs):
pass def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position. Can raise OSError for non seekable files.
"""
pass def seek(self, *args, **kwargs): # real signature unknown
"""
Move to new file position and return the file position. Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable.
"""
pass def write(self, *args, **kwargs): # real signature unknown
"""
Write bytes b to file, return number written. Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass def flush(self, *args, **kwargs):
pass def truncate(self, *args, **kwargs): # real signature unknown
"""
Truncate the file to at most size bytes and return the truncated size. Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""
pass def close(self): # real signature unknown; restored from __doc__
"""
Close the file. A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""
pass
##############################################################less usefull
def fileno(self, *args, **kwargs): # real signature unknown
""" Return the underlying file descriptor (an integer). """
pass def isatty(self, *args, **kwargs): # real signature unknown
""" True if the file is connected to a TTY device. """
pass def readable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a read mode. """
pass def readall(self, *args, **kwargs): # real signature unknown
"""
Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""
pass def seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass def writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
pass

操作方法介绍

f = open('小重山') #打开文件
# data1=f.read()#获取文件内容
# data2=f.read()#获取文件内容
#
# print(data1)
# print('...',data2)
# data=f.read(5)#获取文件内容 # data=f.readline()
# data=f.readline()
# print(f.__iter__().__next__())
# for i in range(5):
# print(f.readline()) # data=f.readlines() # for line in f.readlines():
# print(line) # 问题来了:打印所有行,另外第3行后面加上:'end 3'
# for index,line in enumerate(f.readlines()):
# if index==2:
# line=''.join([line.strip(),'end 3'])
# print(line.strip()) #切记:以后我们一定都用下面这种
# count=0
# for line in f:
# if count==3:
# line=''.join([line.strip(),'end 3'])
# print(line.strip())
# count+=1 # print(f.tell())
# print(f.readline())
# print(f.tell())#tell对于英文字符就是占一个,中文字符占三个,区分与read()的不同.
# print(f.read(5))#一个中文占三个字符
# print(f.tell())
# f.seek(0)
# print(f.read(6))#read后不管是中文字符还是英文字符,都统一算一个单位,read(6),此刻就读了6个中文字符 #terminal上操作:
f = open('小重山2','w')
# f.write('hello \n')
# f.flush()
# f.write('world') # 应用:进度条
# import time,sys
# for i in range(30):
# sys.stdout.write("*")
# # sys.stdout.flush()
# time.sleep(0.1) # f = open('小重山2','w')
# f.truncate()#全部截断
# f.truncate(5)#全部截断 # print(f.isatty())
# print(f.seekable())
# print(f.readable()) f.close() #关闭文件

接下来我们继续扩展文件模式:

# f = open('小重山2','w') #打开文件
# f = open('小重山2','a') #打开文件
# f.write('莫等闲1\n')
# f.write('白了少年头2\n')
# f.write('空悲切!3') # f.close() #r+,w+模式
# f = open('小重山2','r+') #以读写模式打开文件
# print(f.read(5))#可读
# f.write('hello')
# print('------')
# print(f.read()) # f = open('小重山2','w+') #以写读模式打开文件
# print(f.read(5))#什么都没有,因为先格式化了文本
# f.write('hello alex')
# print(f.read())#还是read不到
# f.seek(0)
# print(f.read()) #w+与a+的区别在于是否在开始覆盖整个文件 # ok,重点来了,我要给文本第三行后面加一行内容:'hello 岳飞!'
# 有同学说,前面不是做过修改了吗? 大哥,刚才是修改内容后print,现在是对文件进行修改!!!
# f = open('小重山2','r+') #以写读模式打开文件
# f.readline()
# f.readline()
# f.readline()
# print(f.tell())
# f.write('hello 岳飞')
# f.close()
# 和想的不一样,不管事!那涉及到文件修改怎么办呢? # f_read = open('小重山','r') #以写读模式打开文件
# f_write = open('小重山_back','w') #以写读模式打开文件 # count=0
# for line in f_read:
# if count==3:
# f_write.write('hello,岳飞\n')
#
# else:
# f_write.write(line) # another way:
# if count==3:
#
# line='hello,岳飞2\n'
# f_write.write(line)
# count+=1 # #二进制模式
# f = open('小重山2','wb') #以二进制的形式读文件
# # f = open('小重山2','wb') #以二进制的形式写文件
# f.write('hello alvin!'.encode())#b'hello alvin!'就是一个二进制格式的数据,只是为了观看,没有显示成010101的形式

注意1:  无论是py2还是py3,在r+模式下都可以等量字节替换,但没有任何意义的! 

注意2:有同学在这里会用readlines得到内容列表,再通过索引对相应内容进行修改,最后将列表重新写会该文件。

这种思路有一个很大的问题,数据若很大,你的内存会受不了的,而我们的方式则可以通过迭代器来优化这个过程。 

补充:rb模式以及seek

在py2中:

#昨夜寒蛩不住鸣.

f = open('test','r',) #以写读模式打开文件

f.read(3)

# f.seek(3)
# print f.read(3) # 夜 # f.seek(3,1)
# print f.read(3) # 寒 # f.seek(-4,2)
# print f.read(3) # 鸣

在py3中:

# test:
昨夜寒蛩不住鸣. f = open('test','rb',) #以写读模式打开文件 f.read(3) # f.seek(3)
# print(f.read(3)) # b'\xe5\xa4\x9c' # f.seek(3,1)
# print(f.read(3)) # b'\xe5\xaf\x92' # f.seek(-4,2)
# print(f.read(3)) # b'\xe9\xb8\xa3' #总结: 在py3中,如果你想要字符数据,即用于观看的,则用r模式,这样我f.read到的数据是一个经过decode的
# unicode数据; 但是如果这个数据我并不需要看,而只是用于传输,比如文件上传,那么我并不需要decode
# 直接传送bytes就好了,所以这个时候用rb模式. # 在py3中,有一条严格的线区分着bytes和unicode,比如seek的用法,在py2和py3里都是一个个字节的seek,
# 但在py3里你就必须声明好了f的类型是rb,不允许再模糊. #建议: 以后再读写文件的时候直接用rb模式,需要decode的时候仔显示地去解码.

1.4 with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:
pass

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
pass

 

 

  

python(11)- 文件处理的更多相关文章

  1. python 读写文件和设置文件的字符编码

    一. python打开文件代码如下: f = open("d:\test.txt", "w") 说明:第一个参数是文件名称,包括路径:第二个参数是打开的模式mo ...

  2. Python的文件与文件夹操作

    Python的文件与文件夹操作 Python OS模块 1.重命名:os.rename(old, new) 2.删除:os.remove(file) 3.列出目录下的文件 :os.listdir(pa ...

  3. Python 读写文件操作

    python进行文件读写的函数是open或file file_handler = open(filename,,mode) Table mode 模式 描述 r 以读方式打开文件,可读取文件信息. w ...

  4. Python之文件与目录操作及压缩模块(os、shutil、zipfile、tarfile)

    Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模 ...

  5. python之文件的读写和文件目录以及文件夹的操作实现代码

    这篇文章主要介绍了python之文件的读写和文件目录以及文件夹的操作实现代码,需要的朋友可以参考下 为了安全起见,最好还是给打开的文件对象指定一个名字,这样在完成操作之后可以迅速关闭文件,防止一些无用 ...

  6. 文件操作mode学习总结-----Python学习总结【第四篇】:Python之文件操作(文件、正则、json、pickle)

    非常全的博客,防丢链接参考https://www.cnblogs.com/madsnotes/articles/5521551.html 1.文件操作 1.1 操作流程 1)文件打开 2)文件操作 3 ...

  7. 【转】Python之文件与目录操作(os、zipfile、tarfile、shutil)

    [转]Python之文件与目录操作(os.zipfile.tarfile.shutil) Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读 ...

  8. Python打包文件夹的方法小结(zip,tar,tar.gz等)

    本文实例讲述了Python打包文件夹的方法.分享给大家供大家参考,具体如下: 一.zip ? 1 2 3 4 5 6 7 8 9 10 11 import os, zipfile #打包目录为zip文 ...

  9. Python之文件与目录操作(os、zipfile、tarfile、shutil)

    Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模 ...

  10. Python OS 文件/目录方法

    Python OS 文件/目录方法 os 模块提供了非常丰富的方法用来处理文件和目录.常用的方法如下表所示: 序号 方法及描述 1 os.access(path, mode) 检验权限模式 2 os. ...

随机推荐

  1. [python IO学习篇] 补充中文编码

    http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386820066616a7 ...

  2. POJ 2021 Relative Relatives

    Relative Relatives Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 3339   Accepted: 146 ...

  3. C/C++、Java、Python谁是编译型语言,谁是解释型语言?

    最近各大互联网公司线上笔试,编程题目里的编译器只支持C/C++.Java,甚至有的支持javaScrpit和Pascal,就是不支持Python.让一直以来用惯了Python的我直吐血,于是今天痛定思 ...

  4. 完全平方数(bzoj 2440)

    Description 小 X 自幼就很喜欢数.但奇怪的是,他十分讨厌完全平方数.他觉得这些数看起来很令人难受.由此,他也讨厌所有是完全平方数的正整数倍的数.然而这丝毫不影响他对其他数的热爱. 这天是 ...

  5. 【NOIP2016练习】T2 旅行(树形DP,换根)

    题意:小C上周末和他可爱的同学小A一起去X湖玩. X湖景区一共有n个景点,这些景点由n-1条观光道连接着,从每个景点开始都可以通过观光道直接或间接地走到其他所有的景点.小C带着小A从1号景点开始游玩. ...

  6. net5:自定义验证控件服务器端验证与客户端验证的使用

    原文发布时间为:2008-07-29 -- 来源于本人的百度文章 [由搬家工具导入] using System;using System.Data;using System.Configuration ...

  7. Atcoder CODE FESTIVAL 2017 qual B D - 101 to 010 dp

    题目链接 题意 对于一个\(01\)串,如果其中存在子串\(101\),则可以将它变成\(010\). 问最多能进行多少次这样的操作. 思路 官方题解 转化 倒过来考虑. 考虑,最终得到的串中的\(' ...

  8. TStringList,快速解析 查找测试。。。很有用,再也不用 FOR 循环了

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABKAAAALHCAIAAAA2Gq0zAAAgAElEQVR4nOydeVgUV76wK5OZb5JJZi

  9. CUDA程序计时

    之前写的CUDA程序,想测量一下性能,网上很多用的是CPU端计时,很不准确.翻了一下书,发现这里应该使用事件来计时. CUDA中的事件本质上是一个GPU时间戳,这个时间戳是在用户指定的时间点上记录的. ...

  10. tableView刷新中的问题

    在开始之前先上一张效果图 相信大家都看到了“店铺优惠”这一栏,在这里假设这一栏就是单独的一个cell,当无店铺优惠的时候不可点击在有店铺优惠的时候会弹出优惠列表,选中并返回时会刷新数据,所以弹出视图采 ...