Python Introductory article file _python

Source: Internet
Author: User
Tags glob object serialization readline serialization string format

Functions and methods of file processing

Use the open () function to open the file in the following syntax format:

Copy Code code as follows:

File_handler = open (Filename,[,mode[,bufsize]]

FileName is the name of the file you want to manipulate, if not the current path, you need to indicate the specific path. Mode is the pattern that opens the file, indicating how you want to manipulate the file, bufsize whether caching is used.

Mode

Mode Description
R Open the file as read and read the file information.
W Opens the file as a write to write information to the file.
A Opens the file as an append, and the file pointer is automatically moved to the end of the file.
r+ Opens the file read-write and reads and writes the file.
w+ Erase the contents of the file, and then open the file in read-write mode.
A + Open the file as read-write and move the file pointer to the end of the file.
B Opens the file in binary mode, rather than in text mode. This mode is only valid for Windows or DOS, and Unix-like files are operated in binary mode.

BufSize

bufsize Value Description
0 Disable buffering
1 Row buffering
>1 Specifies the size of the buffer
<1 system default Buffer size

The open () function returns a file object where we can read and write files through the read () or write () functions, and the following are some file object methods:

File Object Methods

Method Description
F.close () Close the file and remember to turn it off after opening the file with open (), or it will take up the number of open file handles to the system.
F.fileno () Get file Descriptor
F.flush () Refreshing output caching
F.isatty () Returns true if the file is an interactive terminal, or false.
F.read ([Count]) Reads out the file and, if there is count, reads count bytes.
F.readline () Read a line of information.
F.readlines () Read all lines, that is, read the entire file information.
F.seek (Offset[,where]) Move the file pointer to the offset position relative to the where. The offset of 0 indicates the beginning of the file, this is the default value, 1 indicates the current position; 2 indicates the end of the file.
F.tell () Gets the location of the file pointer.
F.truncate ([size]) Intercepts the file so that the file is of size.
F.write (String) Writes a string string to a file.
F.writelines (list) Writes a string of strings in a list to a file.

Example

1. Open or create a file

Copy Code code as follows:

#!/usr/bin/env python
#-*-Encoding:utf-8-*-

Filehandler = open (' Test.txt ', ' W ') #以写模式打开文件, created if the file does not exist
Filehandler.write (' This are a file Open/create test.\nthe second line. ')

Filehandler.close ()
#!/usr/bin/env python
#-*-Encoding:utf-8-*-

Filehandler = open (' Test.txt ', ' a ') #以追加模式打开文件, created if the file does not exist

Filehandler.write (' \nappend the text in another line.\n ')

Filehandler.close ()

2. Read the file

Copy Code code as follows:

#!/usr/bin/env python
#-*-Encoding:utf-8-*-

Filehandler = open (' Test.txt ', ' R ') #以读方式打开文件, RB is binary (such as a picture or executable file, etc.)

print ' Read () function: ' #读取整个文件
Print Filehandler.read ()

print ' ReadLine () function: ' #返回文件头, reading a row
Filehandler.seek (0)
Print Filehandler.readline ()

print ' ReadLines () function: ' #返回文件头, returns a list of all rows
Filehandler.seek (0)
Print Filehandler.readlines ()

print ' List all lines ' #返回文件头, showing all rows
Filehandler.seek (0)
Textlist = Filehandler.readlines ()
For line in Textlist:
Print Line

print ' Seek () function ' #移位到第32个字符, starting with 33 characters to display the rest
Filehandler.seek (32)
Print Filehandler.read ()

print ' Tell () function ' #移位到文件头, displaying 2-bit characters from the beginning
Filehandler.seek (0)
Print Filehandler.readline () #显示第一行内容
Print Filehandler.tell () #显示当前位置
Print Filehandler.readline () #显示第二行内容
Print Filehandler.read () #显示余下所有内容

Filehandler.close () #关闭文件句柄

3. File System operation

Copy Code code as follows:

#!/usr/bin/env python
#-*-Encoding:utf-8-*-

Import Os,fnmatch,glob

For FileName in Os.listdir ('/root '): #列出/root directory contents, excluding.
Print FileName

Os.mkdir (' py ') #在当前目录下创建一个py目录, and only one layer can be created
Os.rmdir (' py ') #在当前目录下删除py目录, and only one level can be deleted
Os.makedirs (' Py/aa ') #可创建多层目录
Os.removedirs (' Py/aa ') #可删除多层目录


print ' Demonstration Fnmatch module '
For FileName in Os.listdir ('/root/python/file '):
If Fnmatch.fnmatch (fileName, ' *.txt '): #利用UNIX风格的通配, only files with a suffix of txt are displayed
Print FileName

print ' Demonstration glob module '
For FileName in Glob.glob (' *.txt '): #利用UNIX风格的通配, only files with a suffix of txt are displayed
Print FileName

4. Get File status

Copy Code code as follows:

#!/usr/bin/env python
#-*-Encoding:utf-8-*-

Import Os,time,stat

Filestats = Os.stat (' test.txt ')                           #获取文件/Directory status
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]                           #获取文件的模式
}
#print fileInfo

For field in FileInfo: #显示对象内容
print '%s:%s '% (Field,fileinfo[field])

#for Infofield,infovalue in FileInfo:
# print '%s:%s '% (infofield,infovalue)
If Stat. S_isdir (filestats [Stat. St_mode]): #判断是否路径
print ' Directory. '
Else
print ' Non-directory. '

If Stat. S_isreg (filestats [Stat. St_mode]): #判断是否一般文件
print ' Regular file. '
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. '
#!/usr/bin/env python
#-*-Encoding:utf-8-*-

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

The stat module describes the meaning of the values in the list of file attributes returned by Os.stat (filename). We can conveniently access the values in Os.stat () according to the stat module.

5. Serialization of files

Copy Code code as follows:

#!/usr/bin/env python
#-*-Encoding:utf-8-*-

Import Pickle

Filehandler = open (' Pickle.txt ', ' W ')

Text = [' is a pickle demonstrate ', ' AA ', ' BB ']

Pickle.dump (Text,filehandler) #把text的内容序列化后保存到pickle. txt file

Filehandler.close ()

Filehandler2 = open (' Pickle.txt ')

Textlist = Pickle.load (filehandler2) #还原序列化字符串
Print Textlist

Filehandler2.close ()

#cpickle是用C写的pickle模块, much faster than the standard pickle, the use of methods with pickle.

6. Memory Files

Copy Code code as follows:

#!/usr/bin/env python
#-*-Coding:utf-8-*-

Import Stringio

FileHandle = Stringio.stringio ("Let Freedom Ring.") #create file in memory

Print Filehandle.read () # "Let the Freedom Ring."

Filehandle.close ()

#cStringIO是用C写的StringIO模块, execution speed is faster than Stringio.

The Shutil module is an advanced file processing module, which can be used to copy and delete files.

Open File
The Open File program calls the built-in open function, first the external name, and then the processing mode.

Common file Operations:

In any case, a text file in a Python program takes the form of a string, and text is returned as a string when the text is read

The data read from the file is a string when it returns to the script, so if the string is not what you want, you have to convert it to another type of Python object

Files in the actual application
First look at a simple example of a file processing:

Copy Code code as follows:

>>> myfile=open (' myfile ', ' W ')
>>> myfile.write (' hello,myfile!\n ')
>>> Myfile.close ()
>>> myfile=open (' myfile ')
>>> Myfile.readline ()
' Hello,myfile!\n '
>>> Myfile.readline ()
''

Writes a line of text as a string containing a line terminator \ nthe write method does not add a line terminator to us

Storing and parsing Python objects in a file
You must use the conversion tool to convert the object to a string, noting that the file data must be a string in the script, and the Write method does not automatically do any work for us to convert to string format

Copy Code code as follows:

>>> x,y,z=43,324,34
>>> s= ' Spam '
>>> d={' A ': 1, ' B ': 2}
>>> l=[1,2,3]
>>> f=open (' Datafile.txt ', ' W ')
>>> f.write (s+ ' \ n ')
>>> f.write ('%s,%s,%s\n '% (x,y,z))
>>> f.write (str (L) + ' $ ' +str (D) + ' \ n ')
>>> F.close ()

Once we create a file love You can view the contents of a file by opening and reading the string, while the print statement interprets the result of the inline line terminator to the user:

Copy Code code as follows:

>>> bytes=open (' Datafile.txt '). Read ()
>>> bytes
"Spam\n43,324,34\n[1, 2, 3]${' a ': 1, ' B ': 2}\n"
>>> Print bytes
Spam
43,324,34
[1, 2, 3]${' a ': 1, ' B ': 2}

Since Python does not automatically convert strings to numbers or other types of objects, you need to use common object tools such as indexes, additions, and so on.

Copy Code code as follows:

>>> f=open (' Datafile.txt ')
>>> Line=f.readline ()
>>> Line
' Spam\n '
>>> Line=f.readline ()
>>> Line
' 43,324,34\n '
>>> parts=line.split (', ')
>>> Parts
[' The ', ' 324 ', ' 34\n ']
>>> Int (parts[1])
324
>>> Numbers=[int (p) for p in parts]
>>> numbers
[43, 324, 34]
>>> Line=f.readline ()
>>> Line
"[1, 2, 3]${' a ': 1, ' B ': 2}\n"
>>> parts=line.split (' $ ')
>>> Parts
[' [1, 2, 3] ', ' {' A ': 1, ' B ': 2}\n ']
>>> eval (parts[0])
[1, 2, 3]
>>> Objects=[eval (p) for p in parts]
>>> objects
[[1, 2, 3], {' A ': 1, ' B ': 2}]

Storing Python native objects with pickle
Using eval to convert strings to objects, the Pickle module is an advanced tool that allows us to store almost any Python object directly in a file, and does not require the conversion of strings to

Copy Code code as follows:

>>> f=open (' Datafile.txt ', ' W ')
>>> Import Pickle
>>> Pickle.dump (d,f)
>>> F.close ()
>>> f=open (' Datafile.txt ')
>>> E=pickle.load (F)
>>> E
{' A ': 1, ' B ': 2}

The Pickle module performs the so-called object serialization, that is, the conversion between the object and the byte string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.