Home Backend Development Python Tutorial 跟老齐学Python之不要红头文件(2)

跟老齐学Python之不要红头文件(2)

Jun 16, 2016 am 08:41 AM

文件的属性

所谓属性,就是能够通过一个文件对象得到的东西。

复制代码 代码如下:

>>> f = open("131.txt","a")
>>> f.name
'131.txt'
>>> f.mode      #显示当前文件打开的模式
'a'
>>> f.closed    #文件是否关闭,如果关闭,返回True;如果打开,返回False
False
>>> f.close()   #关闭文件的内置函数
>>> f.closed
True

文件的有关状态

很多时候,我们需要获取一个文件的有关状态(有时候成为属性,但是这里的文件属性和上面的文件属性是不一样的,可是,我觉得称之为文件状态更好一点),比如创建日期,访问日期,修改日期,大小,等等。在os模块中,有这样一个方法,能够解决此问题:

复制代码 代码如下:

>>> import os
>>> file_stat = os.stat("131.txt")      #查看这个文件的状态
>>> file_stat                           #文件状态是这样的。从下面的内容,有不少从英文单词中可以猜测出来。
posix.stat_result(st_mode=33204, st_ino=5772566L, st_dev=2049L, st_nlink=1, st_uid=1000, st_gid=1000, st_size=69L, st_atime=1407897031, st_mtime=1407734600, st_ctime=1407734600)

>>> file_stat.st_ctime                  #这个是文件创建时间
1407734600.0882277                      #换一种方式查看这个时间
>>> import time                        
>>> time.localtime(file_stat.st_ctime)  #这回看清楚了。
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=11, tm_hour=13, tm_min=23, tm_sec=20, tm_wday=0, tm_yday=223, tm_isdst=0)

以上关于文件状态和文件属性的内容,在对文件的某些方面进行判断和操作的时候或许会用到。特别是文件属性。比如在操作文件的时候,我们经常要首先判断这个文件是否已经关闭或者打开,就需要用到file.closed这个属性来判断了。

文件的内置函数

复制代码 代码如下:

>>> 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']
>>>

这么多内置函数,不会都讲述,只能捡着重点的来实验了。

复制代码 代码如下:

>>> f = open("131.txt","r")
>>> f.read()
'My name is qiwsir.\nMy website is qiwsir.github.io\nAha,I like program\n'
>>>

file.read()能够将文件中的内容全部读取过来。特别注意,这是返回一个字符串,而且是将文件中的内容全部读到内存中。试想,如果内容太多是不是就有点惨了呢?的确是,千万不要去读大个的文件。

复制代码 代码如下:

>>> contant = f.read()
>>> type(contant)

如果文件比较大了,就不要一次都读过来,可以转而一行一行地,用readline

复制代码 代码如下:

>>> f = open("131.txt","r")
>>> f.readline()        #每次返回一行,然后指针向下移动
'My name is qiwsir.\n'
>>> f.readline()        #再读,再返回一行
'My website is qiwsir.github.io\n'
>>> f.readline()
'Aha,I like program\n'
>>> f.readline()        #已经到最后一行了,再读,不报错,返回空
''

这个方法,看官是不是觉得太慢了呢?有没有痛快点的呢?有,请挥刀自宫,不用自宫,也能用readlines。注意区别,这个是复数,言外之意就是多行啦。

复制代码 代码如下:

>>> f = open("131.txt","r")
>>> cont = f.readlines()
>>> cont
['My name is qiwsir.\n', 'My website is qiwsir.github.io\n', 'Aha,I like program\n']
>>> type(cont)

>>> for line in cont:
...     print line
...
My name is qiwsir.

My website is qiwsir.github.io

Aha,I like program

从实验中我们可以看到,readlines和read有一样之处,都是将文件内容一次性读出来,存放在内存,但是两者也有区别,read返回的是str类型,readlines返回的是list,而且一行一个元素,因此,就可以通过for逐行打印出来了。

在print line中,注意观察list里面的每个元素,最后都是一个\n结尾,所以打印的结果会有空行。其原因前面已经介绍过了,忘了的朋友请回滚到上一讲

不过,还是要提醒列位,太大的文件不用都读到内存中。对付大点的文件,还是推荐这么做:

复制代码 代码如下:

>>> f = open("131.txt","r")
>>> f

>>> type(f)

>>> for line in f:
...     print line
...
My name is qiwsir.

My website is qiwsir.github.io

Aha,I like program

以上都是读文件的内置函数和方法。除了读,就是要写。所谓写,就是将内容存入到文件中。用到的内置函数是write。但是,要写入文件,还要注意打开文件的模式,可以是w,也可以是a,看具体情况而定。

复制代码 代码如下:

>>> f = open("131.txt","a")     #因为这个文件已经存在,我又不想清空,用追加的模式
>>> f.write("There is a baby.") #这句话应该放到文件最后
>>> f.close()                   #请看官注意,写了之后,一定要及时关闭文件。才能代表真正写入

看看写的效果:

复制代码 代码如下:

>>> f = open("131.txt","r")
>>> for line in f.readlines():
...     print line
...
My name is qiwsir.

My website is qiwsir.github.io

Aha,I like program

There is a baby.        #果然增加了这一行


以上是关于文件的基本操作。其实对文件远远不知这些,有兴趣的看官可以google一下pickle这个模块,是一个很好用的东西。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles