search
HomeBackend DevelopmentPython Tutorial跟老齐学Python之不要红头文件(2)

文件的属性

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

复制代码 代码如下:

>>> 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
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
Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python in Action: Real-World ExamplesPython in Action: Real-World ExamplesApr 18, 2025 am 12:18 AM

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python's Main Uses: A Comprehensive OverviewPython's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AM

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor