您的位置:首页 > 编程语言 > Python开发

python-文件操作

2016-05-27 00:27 603 查看

文件操作

文件的操作,一般需要经历如下步骤:

打开文件

操作文件

关闭文件

一.打开文件

python打开文件有两种方式,即:open(...)和file(...)

本质上前者在内部会调用后者来进行文件操作,推荐使用 open。3.0以后file方法讲被用做其他,open方法会自动的去帮你找他调用得方法在那里!

文件句柄 = open('文件路径','模式') #文件全路径


打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

r,只读模式(默认)。

w,只写模式。【不可读;不存在则创建,存在则清空内容】

a,追加模式。【可读;不存在则创建,存在则只追加内容】

'+'表示可以同时读写某个文件

r+,可读取文件。【可读,可写,可追加】

w+,先写再读,【这个方法打开文件会清空原本文件中的所有内容,将新的内容写进去,之后可以读取已经写入的内容】

a+,同a

"b"表示以字节的方式操作

rb 或 r+b

wb 或 w+b

xb 或 w+b

ab 或 a+b

r和rb的区别:

class file(object):

def close(self): # real signature unknown; restored from __doc__
关闭文件

"""close() -> None or (perhaps) an integer.  Close the file.

Sets data attribute .closed to True.  A closed file cannot be used for
further I/O operations.  close() may be called more than once without
error.  Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
"""

def fileno(self): # real signature unknown; restored from __doc__
文件描述符

"""fileno() -> integer "file descriptor".

This is needed for lower-level file interfaces, such os.read(). """

return 0

def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区

""" flush() -> None.  Flush the internal I/O buffer. """

pass

def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备

""" isatty() -> true or false.  True if the file is connected to a tty device. """

return False

def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错

""" x.next() -> the next value, or raise StopIteration """

pass

def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据

"""read([size]) -> read at most size bytes, returned as a string.

If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given."""

pass

def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃

""" readinto() -> Undocumented.  Don't use this; it may go away. """

pass

def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""readline([size]) -> next line from the file, as a string.

Retain newline.  A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF. """

pass

def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表

"""readlines([size]) -> list of strings, each a line from the file.

Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned. """

return []

def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""seek(offset[, whence]) -> None.  Move to new file position.

Argument offset is a byte count.  Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file).  If the file is opened in text mode,
only offsets returned by tell() are legal.  Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable. """

pass

def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置

""" tell() -> current file position, an integer (may be a long integer). """
pass

def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据

""" truncate([size]) -> None.  Truncate the file to at most size bytes.

Size defaults to the current file position, as returned by tell().“""

pass

def write(self, p_str): # real signature unknown; restored from __doc__
写内容

"""write(str) -> None.  Write string str to file.

Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written."""

pass

def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""writelines(sequence_of_strings) -> None.  Write the strings to the file.

Note that newlines are not added.  The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string. """

pass

def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部

"""xreadlines() -> returns self.

For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module. """

pass

file Code


文件操作源码

读文件操作:

read([size]):读取文件全部内容,如果设置了size,那么就读取size字节。

# 以只读的方式打开文件ha2.log
f = open("hello.txt","r")
# 读取文件内容赋值给变量c
a = f.read(6) #如果加size,则读取size个字符, 注意读取指针的位置 但是如果文件过大,可能造成内存溢出问题
b = f.read() #如果没加size,则全部读取。 注意,会根据上面的指针继续读取到结尾。
# 关闭文件
f.close()
# 输出a,b的值
print 'a=', a
print 'b=', b

  输出结果:
  a= 66666
  b= 667777
  dasdasdadsa
  asdasdasdasd
  asdasdads22222222


ha2.log文件内容:



readline([size]):仅读取一行数据,如果设置了size,那么就读取size字节。

#以只读的方式打开文件hello.txt
f = open('ha2.log','r')
# 读取文件内容赋值给变量c
a = f.readline(5) #只读取一行,如果加了size 只去读对应数量的字符
b = f.readline() #只读取一行,如果没加size 只去一整行。
c = f.readline()#每调用一次,读取一行
# 关闭文件
f.close()
# 输出a,b的值
print 'a=',a
print 'b=',b
print 'c=',c


readlines():读取所有数据,并根据换行保存值列表.

#以只读的方式打开文件hello.txt
f = open('ha2.log','r')
# 读取文件内容赋值给变量c
a = f.readlines() #读取全部信息,并以列表的形式保存,但是如果文件过大,可能造成内存溢出问题
# 关闭文件
f.close()
# 输出a的值
print 'a=',a


写文件操作:

write(str) 将字符串写入到文件中,原文件内容存在则清空,不存在新建。

#以只读的方式打开文件hello.txt
f = open('ha2.log','w') #这个是本地存在文件,其中存在内容
f1 = open('ha3.log','w')#这个是本地不存在文件
#在文件内容中写入字符串this is a test123
f.write('this is a test123')
f.write('sssssssssssss')#如果不在上语句加上\n就会写在后面,请注意换行符的使用
f1.write('this is a test123')
f1.write('sssssssssssss')
#关闭文件
f.close()
f1.close()


结果:

ha2.log之前的内容:            现在的内容:


   


writelines(str) 功能类似只是可以写多行到文件,参数可以是一个可迭代的对象,列表、元组等。

注意:这些可迭代对象的元素必须是字符串。不然会报错 TypeError: writelines() argument must be a sequence of strings

a1 = ['111','222','333','444'] #元素必须是字符串
a2 = ('aaaa','bbbb','ccccc')
a3 = {'ffff':123,'gggg':456}
#以只读的方式打开文件hello.txt
f = open('ha2.log','w') #这个是本地存在文件,其中存在内容
#在文件内容中写入字符串this is a test123
f.writelines(a3)#如果不在上语句加上\n就会写在后面,请注意换行符的使用
#关闭文件
f.close()


其他操作(主要→次要):

tell(self),获取指针的位置,没有参数:

a1 = ['111','222','333','444']
a2 = ('aaaa','bbbb','ccccc')
a3 = {'ffff':123,'gggg':456}
#以可读可写的方式打开文件hello.txt
f = open('ha2.log','r+') #这个是本地存在文件,其中存在内容
#在文件内容中写入字符串this is a test123
print '位置1:',f.tell()#获取当前指针位置,注意在打开文件的时候指针总是在最开始的位置,
f.writelines(a2)#如果不在上语句加上\n就会写在后面,请注意换行符的使用
print '位置2:',f.tell()#获取当前指针位置
#关闭文件
f.close()


tell的作用是指出当前指针所在的位置。无论对文件的读或者写,都是依赖于指针的位置,我们从指针的位置开始读,也从指针的位置开始写。

结果:



seek(offset),上面的tell函数是获取指针的位置,seek函数可以指定文件中指针位置,这样可根据自己需要设定写入位置。

#以可读可写的方式打开文件hello.txt
f = open('ha2.log','r+') #这个是本地存在文件,其中存在内容
#在文件内容中写入字符串this is a test123
print '位置1:',f.tell()#获取当前指针位置,注意在打开文件的时候指针总是在最开始的位置,
f.seek(4)#指定指针的位置
print '位置2:',f.tell()#获取当前指针位置
#关闭文件
f.close()


truncate(size):保存当前指针位置之前的内容

#以可读可写的方式打开文件hello.txt
f = open('ha2.log','r+') #这个是本地存在文件,其中存在内容
print '第一次读:',f.read()
#在文件内容中写入字符串this is a test123
f.seek(0)#指定指针的位置
f.write('this is a truncate test,***')
f.seek(0)#指定指针的位置
f.write('test test test')
f.truncate()
f.seek(0)
print '第二次读:',f.read()
#关闭文件
f.close()


结果:

第一次读: 111111111111
2222222222222
44444444444444
第二次读: test test test


总结:有上面的打印结果我们可以知道,在文件进行写操作的时候,会根据指针的位置直接覆盖相应的内容,但是很多时候我们修改完文件之后,后面的东西就不想保留 了,这个时候我们使用truncate方法,文件就仅保存当前指针位置之前的内容。我们同样可以使用truncate(n)来保存n之前的内容,n表示指 针位置。

三、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:with open('文件路径','操作方式') as 文件句柄:

#使用whith打开可以不用close
with open('ha2.log','r+') as file_obj:
file_obj.write('')


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

# 文件句柄可以循环,每次1句,写入 另一个文件
with open('ha2.log','r') as obj1, open('ha3.log','w') as obj2:
for line in obj1:
obj2.write(line)


例子:可以对原文件进行修改的时候进行备份,这样可以避免忘记备份啦,方便以后回滚文件

with open('nginx.conf','r') as obj1,open('nginx.conf.new','w') as obj2:
for i in obj1.readlines():
i = i.strip()
print i
obj2.write(i)
obj2.write('\n')

#读取nginx.conf每行然后存储到新的文件nginx.conf.new里!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: