Python学习之文件(一)

19 篇文章 0 订阅
17 篇文章 1 订阅

我们知道,无论是在存储介质上,还是在云端,我们所有的对象的都是以文件的形式存在的,尤其是在Linux系统中,一切都文件。
所以,文件在Python中也是一种数据类型。
那么,文件除了文本文件以外,还有视频,音频,图片,以及很多我们没有见过扩展名的文件。
那么在Python中,文件依然是一个很重要的知识,因为我们在写程序的时候,或者使用程序调用文件的时候,不可能在命令行直接输入那么多代码,最终是要将写好的代码进行调试并进行封装。那么,封装起来的这些代码还有代码中要调用的文本、图片、视频、音频都是文件。
从这一个节开始时,学习文件。

文件

那么在Python中,文件都有那些属性和函数呢?

>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
>>> 

从以上列出的可以看出,文件有很多属性和函数,但是我们不可能在这里阐述所有文件的属性和函数,我们只是针对文件的部分和函数进行学习。

打开文件

help(open)
Help on built-in function open in module builtin:

open(…)
open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object.  This is the
preferred way to open a file.

(END)
解释:首选打开文件的方式,使用file( )类型打开一个文件,返回一个文件对象。
open(name)打开一个名为name的文件。
open(name[,mode])以何种模式打开名为name的文件。
笔者使用的系统是Linux系统,所以我所有的文件创建都是在Linux中进行的。 使用的是VI编辑器。

需求,在/pythonFile/file路径下创建一个名为test.txt的文件,并打开读取出文件中的内容。
这个文件中的内容为如下:

[root@python file]# cat test.txt 
#!/usr/bin/env python

#coding:utf-8

this is first file;
this is test file;
the file will be opend;
Please close file if you opened file when you don't used it;
[root@python file]# 

使用Pyothon中的open命令打开文件。

>>> tfile = open("/pythonFile/file/test.txt")
>>> for text in tfile:
...     print text
... 
#!/usr/bin/env python



#coding:utf-8



this is first file;

this is test file;

the file will be opend;

Please close file if you opened file when you don't used it;

>>> 

说明:上述代码中首先定义了一个使用open打开文件的对象,然后通过for循环输出文件中的内容
注意我们发现在上面执行后输出的文本中和原先的文本的差别有点大
原因是:原文本中每一行的后面都有一个换行符“”\n“”当我们把打开文件的对象通过for循环输出时,print 后面也是默认有一个换行符“”\n“”,所以,相当于有两个“”\n\n“”,所以,输出的打开文件的对象时,再次输出一个换行符
那么再print后面在加一个逗号再来进行以下比较。

>>> tfile = open("/pythonFile/file/test.txt")
>>> for text in tfile:
...     print text,
... 
#!/usr/bin/env python

#coding:utf-8

this is first file;
this is test file;
the file will be opend;
Please close file if you opened file when you don't used it;
>>> 

注意,我们可能会遇到在这样一种状况,那就是,当我们再次输出这个文件中的内容时,会什么也得不到。
来试一下。

>>> tfile = open("/pythonFile/file/test.txt")
>>> for text in tfile:
...     print text,
... 
#!/usr/bin/env python

#coding:utf-8

this is first file;
this is test file;
the file will be opend;
Please close file if you opened file when you don't used it;
>>> for line in tfile:
...     print line,
... 
>>> 
>>> for text in tfile:
...      print text,
... 
>>> 

发现,并不是由于变量的原因而导致文本内容无法输出。
其实这个在python中,Python它并不认为这个有错,因为它是为你考虑,它担心你在文件的后面追加了内容,所以,当你 再次输出文件的时候,指针停留在上一次打开文件的末尾。假如在text中再加入这么一行

[root@python file]# cat test.txt 
#!/usr/bin/env python

#coding:utf-8

this is first file;
this is test file;
the file will be opend;
Please close file if you opened file when you don't used it;
这是追加的一行内容,用来做测试。
[root@python file]# 

上述代码中的中文为新写入的内容

for text in tfile:
… print text,

但是在执行for循环后依然没有得到文件中的内容,这是为什么呢??
接下来找原因

创建文件

上面我们学习了如何打开已经存在的文件,但是我们要怎么创建一个文件呢?这个做法在我们写网络爬虫的时候特别需要,比如我们要爬虫一个网页的所有内容,并把它保存在存储当中。
可以这样做:

>>> touch = open("/pythonFile/file/touch.txt","w")
>>> touch.write("这是一个测试创建的文本文件")
>>> 

查看文件:
[root@python file]# cat touch.txt
这是一个测试创建的文本文件[root@python file]#

但是这里注意,自己创建并写入的测试语句会在文本文件中看不到,那么怎么做才能让自己看到呢?
这样做,重新打开文件,
我个人理解,由于Python中,当执行write的时候,Python会认为你正在文件中写东西,当你写东西的时候它不会将内容输入到文件中,只有当你执行打开操作或者读操作的时候,Python才会认为你已经完成文件内容的写操作,所以,只有当再次执行open或者read的时候,write的内容才会被写进文件中。

>>> touch = open("/pythonFile/file/touch.txt","w")
>>> touch.write("这是一个测试创建的文本文件")
>>> touch.write("I finished this time")
>>> touch = open("/pythonFile/file/touch.txt")

文件查看:
[root@python file]# ls
test.txt touch.txt
[root@python file]# cat touch.txt
This is test read operate[root@python file]#

发现,我们再创建文件的时候,依然是使用的open模式,但是和之前的open不同的是,我们使用了open中的模式,多加了一个w,这是在告诉Python,我们在以什么样的模式打开文件。

附:open中的打开模式

r 以读取方式打开文件,可以读取文件中的信息
w 以写入的方式打开问阿金,可以向文件中写入信息。如果文件存在,则清空文件,在写入新的内容。
a 以追加的模式打开文件(打开文件,文件指针自动移动到文件末尾),如果文件不存在,则创建
r+ 以读写的方式打开文件,可以对文件进行读取和写入操作。
w+ 消除文件内容,然后以读写方式打开文件
a+ 以读写方式打开文件,并且将文件中的指针移动到末尾
b binary,即以二进制模式打开文件,而不是以文本的模式。该模式只对windows和DOS有效,类unix的文件是用二进制模式进行操作的。

那么上面我们使用open默认的模式是以什么样的方式打开的文件呢。我们可以通过直接输入文件的对象名可以查看,如下:

>>> file = open("/pythonFile/file/test.txt")
>>> file
<open file '/pythonFile/file/test.txt', mode 'r' at 0x1f430c0>
>>> 

发现,使用默认的open文件是以r即只读的方式打开的。
既然这样,那就练习一下几种文件的追加模式吧!
前提:我用的是Linux系统,我在/pythonFile/file/路径下创建了一个文件touch.txt里面的内容如下:
[root@python file]# cat touch.This is test text
这是一个测试文本文件
以下的所有模式的操作都以这个文件为测试文件。
[root@python file]#
以下测试只有代码,不进行解释,如果文件内容有改变,都是依次按照顺序进行测试的。

1、以*w方式打开文件。*

w 以写入的方式打开问阿金,可以向文件中写入信息。如果文件存在,则清空文件,在写入新的内容。

touch = open(“/pythonFile/file/touch.txt”)
for text in touch:
… print text,

This is test text
这是一个测试文本文件
以下的所有模式的操作都以这个文件为测试文件。
touch = open(“/pythonFile/file/touch.txt”,”w”) #文件存在,则清空文件内容,重新写入
touch.write(“This is writing operate”)
touch = open(“/pythonFile/file/touch.txt”)
for text in touch:
… print text,

This is writing operate #验证结果一样

2、以*a模式打开文件*
a 以追加的模式打开文件(打开文件,文件指针自动移动到文件末尾),如果文件不存在,则创建
1)当文件存在

>>> touch = open("/pythonFile/file/touch.txt","a")
>>> touch.write("这个文件是存在的,这一条是追加进去的 !") 
>>> touch = open("/pythonFile/file/touch.txt")
>>> for text in touch:
...     print text,
... 
This is writing operate这个文件是存在的,这一条是追加进去的 !
>>> 

2)当文件不存在

>>> appendtest = open("/pythonFile/file/app.txt","a")
>>> appendtest.write("this file is not exsits in system,\nthis is new created file")
>>> appendtest = open("/pythonFile/file/app.txt")
>>> for text in appendtest:
...     print text,
... 
this file is not exsits in system,
this is new created file
>>> 

3、以读写的方式打开文件

>>> rtest = open("/pythonFile/file/touch.txt","r+")
>>> rtest.write("This is writing in operate")
>>> rtest = open("/pythonFile/file/touch.txt")
>>> rtest.read()
'This is writing in operate\xe4\xb8\xaa\xe6\x96\x87\xe4\xbb\xb6\xe6\x98\xaf\xe5\xad\x98\xe5\x9c\xa8\xe7\x9a\x84\xef\xbc\x8c\xe8\xbf\x99\xe4\xb8\x80\xe6\x9d\xa1\xe6\x98\xaf\xe8\xbf\xbd\xe5\x8a\xa0\xe8\xbf\x9b\xe5\x8e\xbb\xe7\x9a\x84 \xef\xbc\x81'

在这里我用了read函数,但是一下子后面奔出了这么多16进制的符号,让我蒙圈了,所以我就看了一下帮助文档。文档是这么写的:

help(file.read)
Help on built-in function read:

read(…)
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.

(END)
解释:如果size参数为负数或省略,则直到达到EOF为止。
请注意,在非阻塞模式下,数据少于请求的数据
即使没有给出大小参数,也可以返回

反正就是这样,自己看看。后面接触到再进行详细学习。
其余的模式再不一一做详细介绍了

使用with

既然,文件能够被打开,那么,文件当然也可以关闭,在Python中,如果使用了打开文件的模式,一定要在最后记得关闭文件,而关闭文件使用的则是close( )函数

>>> file = open("/pythonFile/file/app.txt")
>>> file.close()
>>> for text in file:
...     print text,
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
>>> 

发现,已经读不出文件了,提示说明:已关闭文件的上的I/O操作。
那么来看一下close( )函数

help(file.close)
Help on built-in function close:

close(…)
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.

:

 解释:将数据属性.closed设置为True。 关闭文件不能用于
 进一步的I / O操作。 close()可能被调用不止一次
 错误。 某些类型的文件对象(例如,由popen()打开)
 关闭时可能返回退出状态。

但是,我们有时候对文件进行了打开操作后,很容易忘记对文件进行关闭,怎么办,使用with

>>> wfile = open("/pythonFile/file/app.txt")
>>> for text in wfile:
...     print text,
... 
this file is not exsits in system,
this is new created file
>>> wfile.close()
>>> with open("/pythonFile/file/app.txt","a") as wf:
...     wf.write("\n这是一个测试with功能的语句\n")
... 
>>> with open("/pythonFile/file/app.txt","r") as rf:
...     print rf.read()
... 
this file is not exsits in system,
this is new created file

这是一个测试with功能的语句

文件的状态

无论什么对象,都会有一个状态,生物的状态就是活着还是死了,自然的状态是有生机还是死气沉沉,太阳的状态是爆发还是稳定等等,文件也是对象,那么文件也会有创建日期,修改日期,访问日期以及大小等,这些都是文件的状态。在Python中,给我们提供了一种查看文件的 状态的方法。那就是OS模块
毫无疑问,我们再使用这个模块之前,要做的首先是导入这个模块。

>>> import os
>>> fstate = os.stat("/pythonFile/file/app.txt")
>>> print fstate
posix.stat_result(st_mode=33188, st_ino=261266, st_dev=2051L, st_nlink=1, st_uid=0, st_gid=0, st_size=99, st_atime=1494415804, st_mtime=1494415773, st_ctime=1494415773)
>>> 

其中st_mode为文件的权限模式,st_ino为文件的编inode编号,st_dev为是否是块设备文件,st_link为是否是链接文件。st_uid为所属用户的id,st_gid为所属用户组的id,st_size为文件的大小,st_atime为文件最近访问的时间,st_mtime为文件最近修改的时间,st_ctime为文件的创建时间。
st_atime=1494415804, st_mtime=1494415773, st_ctime=1494415773)这TMD到底是什么时间,我第一次看到的时候也醉了,不知道是什么时间,但是,幸好我可以借助Python中提供的time模块进行时间的查看,对比一下,一目了然。
文件的创建时间

>>>import time
>>> time.localtime(fstate.st_ctime)
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=10, tm_hour=19, tm_min=29, tm_sec=33, tm_wday=2, tm_yday=130, tm_isdst=0)
>>> 

好了今天关于文件的学习到这里就结束了,不过这只是文件的一部分,Python中,还有一些文件的知识,明天继续。
最近一天计划,先学习完文件,从下一周开始,学习函数。

完成于2017年05月14日
凌晨00:12

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值