`
yesjavame
  • 浏览: 687679 次
  • 性别: Icon_minigender_2
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

python之文件管理

阅读更多
File Management in Python
(Page 1 of 5 )

File management is a basic function, and an important part of many applications. Python makes file management surprisingly easy, especially when compared to other languages. Peyton McCullough explains the basics.
Introduction
The game you played yesterday uses files to store game saves. The order you placed yesterday was saved in a file. That report you typed up this morning was, obviously, stored in a file as well.
File management is an important part of many applications written in nearly every language. Python is no exception to this. In this article, we will explore the task of manipulating files using several modules. We'll read, write to, append and do other strange things to files. Let's get started.
Reading and Writing
The most basic tasks involved in file manipulation are reading data from files and writing data to files. This is a very simple task to learn. Let's open a file for writing:
fileHandle = open ( 'test.txt', 'w' )
The "w" indicates that we will be writing to the file, and the rest is pretty simple to understand. The next step is to write data to the file:
fileHandle.write ( 'This is a test.\nReally, it is.' )
This will write the string "This is a test." to the file's first line and "Really, it is." to the file's second line. Finally, we need to clean up after ourselves and close the file:
fileHandle.close()
As you can see, it's very easy, especially with Python's object orientation. Note that when you use the "w" mode to write to the file again, all its contents will be deleted. To get past this, use the "a" mode to append data to a file, adding data to the bottom:
fileHandle = open ( 'test.txt', 'a' )
fileHandle.write ( '\n\n\nBottom line.' )
fileHandle.close()
Now let's read our file and display the contents:
fileHandle = open ( 'test.txt' )
print fileHandle.read()
fileHandle.close()
This will read the entire file and print the data within it. We can also read a single line in the file:
fileHandle = open ( 'test.txt' )
print fileHandle.readline() # "This is a test."
fileHandle.close()
It is also possible to store the lines of a file into a list:
fileHandle = open ( 'test.txt' )
fileList = fileHandle.readlines()
for fileLine in fileList:
print '>>', fileLine
fileHandle.close()
When reading a file, Python's place in the file will be remembered, illustrated in this example:
fileHandle = open ( 'test.txt' )
garbage = fileHandle.readline()
fileHandle.readline() # "Really, it is."
fileHandle.close()
Only the second line is displayed. We can, however, get past this by telling Python to resume reading from a different position:
fileHandle = open ( 'test.txt' )
garbage = fileHandle.readline()
fileHandle.seek ( 0 )
print fileHandle.readline() # "This is a test."
fileHandle.close()
In the above example, we tell Python to continue reading from the first byte in the file. Thus, the first line is printed. We can also request Python's place within the file:
fileHandle = open ( 'test.txt' )
print fileHandle.readline() # "This is a test."
print fileHandle.tell() # "17"
print fileHandle.readline() # "Really, it is."
It is also possible to read the file a few bytes at a time:
fileHandle = open ( 'test.txt' )
print fileHandle.read ( 1 ) # "T"
fileHandle.seek ( 4 )
print FileHandle.read ( 1 ) # "T"
When working with Windows and Macintosh, sometimes you are required to read and write files in binary mode, such as images or executional files. To do this, simply append "b" to the file mode:
fileHandle = open ( 'testBinary.txt', 'wb' )
fileHandle.write ( 'There is no spoon.' )
fileHandle.close()
fileHandle = open ( 'testBinary.txt', 'rb' )
print fileHandle.read()
fileHandle.close()
Using several of Python's modules, it is possible to obtain information on existig files. To get basic information, the "os" module can be used in conjunction with the "stat" module:
import os
import stat
import time
fileStats = os.stat ( 'test.txt' )
fileInfo = {
'Size' : fileStats [ stat.ST_SIZE ],
'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ),
'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ),
'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ),
'Mode' : fileStats [ stat.ST_MODE ]
}
for infoField, infoValue in fileInfo:
print infoField, ':' + infoValue
if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):
print 'Directory. '
else:
print 'Non-directory.'
The above example creates a dictionary containing some basic information about the file. It then displays the data and tells us if it's a directory or not. We can also check to see if the file is one of several other types:
import os
import stat
fileStats = os.stat ( 'test.txt' )
fileMode = fileStats [ stat.ST_MODE ]
if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ):
print 'Regular file.'
elif stat.S_ISDIR ( fileSTats [ stat.ST_MODe ] ):
print 'Directory.'
elif stat.S_ISLNK ( fileSTats [ stat.ST_MODe ] ):
print 'Shortcut.'
elif stat.S_ISSOCK ( fileSTats [ stat.ST_MODe ] ):
print 'Socket.'
elif stat.S_ISFIFO ( fileSTats [ stat.ST_MODe ] ):
print 'Named pipe.'
elif stat.S_ISBLK ( fileSTats [ stat.ST_MODe ] ):
print 'Block special device.'
elif stat.S_ISCHR ( fileSTats [ stat.ST_MODe ] ):
print 'Character special device.'
Additionally, we canuse "os.path" to gather basic information:
import os.path
fileStats = 'test.txt'
if os.path.isdir ( fileStats ):
print 'Directory.'
elif os.path.isfile ( fileStats ):
print 'File.'
elif os.path.islink ( fileStats ):
print 'Shortcut.'
elif os.path.ismount ( fileStats ):
print 'Mount point.'
File Management in Python - Directories
(Page 3 of 5 )

Directories, like regular files, are easy to work with. Let's start by listing the contents of a directory:
import os
for fileName in os.listdir ( '/' ):
print fileName
As you can see, this is extremely simple, and it can be done in three lines.
Creating a directory is also simple:
import os
os.mkdir ( 'testDirectory' )
It is equally as easy to delete the directory we just created:
import os
os.rmdir ( 'testDirectory )
We can also create multiple directories at a time:
import os
os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
Assuming we add nothing to the directories we just created, we can also delete them all at once:
import os
os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
Suppose we want to perform a specific action when a specific file type is reached. This can easily be done with the "fnmatch" module. Let's print the contents of all the ".txt" files we encounter and print the filename of any ".exe" files we encounter:
import fnmatch
import os
for fileName in os.listdir ( '/' ):
if fnmatch.fnmath ( fileName, '*.txt' ):
print open ( fileName ).read()
elif fnmatch.fnmatch ( fileName, '*.exe' ):
print fileName
The asterisk character can represent any amount of characters. If we want to match just one character, we can use the question mark:
import fnmatch
import os
for fileName in os.listdir ( '/' ):
if fnmatch.fnmatch ( fileName, '?.txt' ):
print 'Text file.'
It is also possible to create a regular expression using the "fnmatch" module, matching filenames with the "re" module:
import fnmatch
import os
import re
filePattern = fnmatch.translate ( '*.txt' )
for fileName in os.listdir ( '/' ):
if re.match ( filePattern, fileName ):
print 'Text file.'
If we're just looking for one type of filename, it is a lot easier to use the "glob" module. Its patterns are similar to those used in "fnmatch":
import glob
for fileName in glob.glob ( '*.txt' ):
print 'Text file.'
It is also possible to use ranges of characters in the patterns, just as you would in regular expressions. Suppose you want to print the names of text files with one digit before the extension:
import glob
for fileName in glob.glob ( '[0-9].txt' ):
print fileName
The "glob" module makes use of the "fnmatch" module.

(Page 4 of 5 )

Using the methods covered in the previous section, it is possible to read strings from files and write strings to files. However, in some situations, you may need to pass other types of data, such as lists, tuples, dictionaries and other objects. In Python, this is possible through a method known as pickling. To pickle data, you would use the "pickle" module included in the standard library.
Let's start by pickling a short list of strings and integers:
import pickle
fileHandle = open ( 'pickleFile.txt', 'w' )
testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]
pickle.dump ( testList, fileHandle )
fileHandle.close()
Unpickling the data is just as easy:
import pickle
fileHandle = open ( 'pickleFile.txt' )
testList = pickle.load ( fileHandle )
fileHandle.cloes()
We can also store more complex data:
import pickle
fileHandle = open ( 'pickleFile.txt', 'w' )
testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ]
pickle.dump ( testList, fileHandle )
fileHandle.close()
import pickle
fileHandle = open ( 'pickleFile.txt' )
testList = pickle.load ( fileHandle )
fileHandle.close()
As you can see, pickling is extremely easy to do with Python's "pickle" module. Numeous objects may be stored in files with it. You can also use the "cPickle" module if it is availible to you. It's exactly the same as the "pickle" modue, but it's faster:
import cPickle
fileHandle = open ( 'pickleFile.txt', 'w' )
cPickle.dump ( 1776, fileHandle )
fileHandle.close()
File Management in Python - Creating In-memory Files
(Page 5 of 5 )

A number of modules you will encounter contain methods that require a file object as an argument. Sometimes, it is inconvenient to create and use a real file, however. Thankfully, you can create files that store themselves in a computer's memory using the "StringIO" module:
import StringIO
fileHandle = StringIO.StringIO ( "Let freedom ring." )
print fileHandle.read() # "Let freedom ring."
fileHandle.close()
A "cStringIO" module is also availible. It is identical to the "StringIO" module in use, but, just like the "cPickle" module is to the "pickle" module, it is faster:
import cStringIO
fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" )
print fileHandle.read() # "To Kill a Mockingbid"
fileHandle.close()
Conclusion
File management is a task that programmers of many languages will often encounter in their applications. Thankfully, Python makes the task incredibly easy compared to other languages. It offers many modules in its standard library that aid programmers, and its object orientation further simplifies things.
You now have a basic understanding of file management in Python, and you will use it in many future applications.


DISCLAIMER: The content provided in this article is not warrantied or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation best practices. We are not liable for any negative consequences that may result by implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.
分享到:
评论

相关推荐

    Python基于Django框架的文档管理系统源码.zip

    Python基于Django框架的文档管理系统源码是一个用于创建、存储和管理文档的Web应用程序,它利用了Python的强大功能和Django框架的高效开发特性。Django是一个开源的、基于模型-视图-控制器(MVC)设计模式的高级Web...

    python文件管理系统各种版本

    Python文件管理系统是用于组织、操作和管理计算机上文件的一种实用工具。这个系统可以有多种实现方式,根据不同的功能和复杂程度分为不同的版本。在你提到的"python文件管理系统各种版本"中,我们可以看到三个主要的...

    基于python与Flask的文件管理系统

    基于python与Flask的文件管理系统,主要功能有: 1、文件的上传和下载 2、消息发送和恢复 3、文件信息的增删改查 4、系统的登录和注册 使用的是mysql数据库,适合初学者下载使用。

    Python S60 文件管理器源程序

    Python S60 文件管理器源程序是一个专门为S60平台设计的文件操作工具,它使用Python编程语言实现。S60(Series 60)是诺基亚开发的一种基于Symbian操作系统上的用户界面,广泛应用于早期的智能手机。Python S60 文件...

    基于Python实现的实验信息综合管理系统.7z,python学生信息管理系统实验报告,Python

    .7z是压缩文件格式,意味着所有相关的源代码、文档和其他资源都被打包在这样一个文件中。 【描述分析】 描述中提到,“基于python实现实验室管理系统,可以实现查询等功能”,这表明这个系统主要服务于实验室环境,...

    Python GUI项目:文件夹管理系统代码

    总之,Python GUI文件夹管理系统是一个结合了Tkinter、文件操作和事件驱动编程的综合项目。通过此项目,开发者不仅可以学习到如何创建GUI应用,还能加深对文件系统操作的理解。实践中,要注意用户体验、错误处理和...

    python学生管理系统源码文件

    python学生管理系统源码文件

    python课程设计仓库管理系统,包含源码,文档,ppt(改良版)

    python课程设计仓库管理系统,包含源码,文档,ppt 仓库管理系统应解决一些问题,例如:非常依赖人工经验,新手上手速度慢;对正在进行的现场作业的可见度不高;缺乏日常仓库作业报表,无法为管理者提供更多数据...

    学生信息管理系统(python+GUI+mysql).zip

    学生信息管理系统(python+GUI+mysql).zip,学生信息管理系统(python+GUI+mysql).zip,学生信息管理系统(python+GUI+mysql).zip 学生信息管理系统(python+GUI+mysql).zip,学生信息管理系统(python+GUI+mysql).zip,...

    基于python的图书管理系统

    【基于Python的图书管理系统】是一种使用Python编程语言开发的应用程序,用于高效地管理和维护图书馆的图书资源。Python因其丰富的库支持和简洁的语法而成为开发此类系统的理想选择。在这个系统中,开发者可能利用了...

    python界面图书管理系统—GUI界面版

    设计一个GUI界面的系统,模拟图书管理,一个面向学生和学校管理员的系统,图书信息以txt文件存在本地。 管理员:查询图书 增加图书 删除图书 学生:借阅图书 归还图书 任何一个操作都会将所更新的图书信息存入本地...

    python大作业仓库管理系统.7z

    Python的内置os、shutil和pickle模块可以协助进行文件的读写和管理。 7. 异常处理:为了确保程序的健壮性,系统可能会包含异常处理机制,使用try/except块捕获并处理可能出现的错误。 8. 单元测试:为了验证代码的...

    Python Linux系统管理与自动化运维

    1. 自动化脚本:Python可以编写简洁的脚本来执行常见的系统管理任务,如文件操作、用户管理、网络配置等,大大提高了效率。 2. 安装与卸载软件:Python的`subprocess`模块可以调用shell命令,实现软件的安装(如`...

    Python资产评估后台管理系统源码.zip

    Python资产评估后台管理系统源码 Python资产评估后台管理系统源码 Python资产评估后台管理系统源码 Python资产评估后台管理系统源码 Python资产评估后台管理系统源码 Python资产评估后台管理系统源码 Python...

    一个Python开发的小型磁盘文件管理系统源码.zip

    这是一个基于Python开发的小型磁盘文件管理系统源码项目,它为用户提供了一种简单的方式来管理和组织计算机上的文件。Python作为一种强大的、易读性高的编程语言,是进行此类开发的理想选择,尤其适合初学者和快速...

    python课程设计:学生成绩管理系统

    压缩包中的"Python】学生成绩管理系统"可能包含了源代码文件、配置文件、数据库脚本、可能还有其他辅助资源。合理的文件组织对于项目的可维护性和可扩展性至关重要。 通过以上知识点的学习和实践,学生不仅可以...

    Python图书管理系统源码.zip

    5. 文件操作:如果系统包含导入导出图书数据的功能,Python的内置`open()`函数和`csv`模块可用于处理文本文件,`pickle`模块则可以用于序列化和反序列化Python对象,便于数据交换。 6. 异常处理:在处理用户输入和...

    python3.8中文帮助文档 离线CHM版

    10. **上下文管理器**:通过 `with` 语句实现的上下文管理器,可以自动处理资源的获取和释放,比如文件操作或数据库连接。 11. **内置函数和常量**:Python 拥有丰富的内置函数,如 len()、range()、zip() 和 ...

    名片管理系统(控制台)Python

    在【标签】"python 名片管理系统"中,"python"指的是系统使用的编程语言,Python以其简洁的语法和强大的功能,成为了初学者入门编程的首选语言之一。"名片管理系统"则表明了项目的核心功能,即存储和管理名片信息,...

    Python3.8.2中文API文档

    10. **安装 Python 模块**:讲解了如何使用 pip 等工具来安装第三方模块,以及处理依赖关系和管理不同版本的 Python 模块。 11. **标准库参考**:Python 标准库包含了大量预先编写的模块,涵盖网络通信、文件处理、...

Global site tag (gtag.js) - Google Analytics