`

python file

 
阅读更多

 

打开文件file_handler = open(filename,mode)

open(filename[, mode[, bufsize]])

Open a file, returning an object of the file type described in section File Objects. If the file cannot be opened, IOError is raised. When opening a file, it’s preferable to use open() instead of invoking the file constructor directly.

The first two arguments are the same as for stdio‘s fopen: filename is the file name to be opened, and mode is a string indicating how the file is to be opened.

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

The optional bufsize argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used. [2]

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

In addition to the standard fopen values mode may be 'U' or 'rU'. Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.

Python enforces that the mode, after stripping 'U', begins with 'r', 'w' or 'a'.

Python provides many file handling modules including fileinput, os, os.path, tempfile, and shutil.

Changed in version 2.5: Restriction on first letter of mode string introduced.

 

    mode:
    r 只读
    w 写,覆盖已有内容。
    a 追加模式,如果文件不存在则创建
    r+ 读写
    w+ 消除文件内容,然后以读写方式打开文件。
    a+ 读写方式,并把文件指针移到文件尾。
    b 二进制模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。
    读取文件内容

File Objects

        File objects are implemented using C’s stdio package and can be created with the built-in open() function. File objects are also returned by some other built-in functions and methods, such as os.popen() and os.fdopen() and the makefile() method of socket objects. Temporary files can be created using the tempfile module, and high-level file operations such as copying, moving, and deleting files and directories can be achieved with the shutil module.

        When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.

 
    f.read([count]) 读出文件,如果有count,则读出count个字节。Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.


    f.readline() 读出一行信息。


    f.readlines()读出所有行,也就是读出整个文件的信息。写入文件内容


    f.write(string)把string字符串写入文件。


    f.writelines(list) 把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。

    换行符在各个操作系统中界定的不同,Windows换行符是‘\r\n',Unix/Linux的换行符为'\n',Mac的换行符为'\r';
    在python中,对换行符进行了统一处理,定义为'\n',以文本模式写入时,如果是Windows系统,则python会自动将\n转为\r\n,Mac系统类似


文件指针操作
    f.seek(offset[,where]) 把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值 ;1表示当前位置;2表示文件结尾。


    f.tell()获得文件指针位置。


文件信息操作
    f.fileno()获得文件描述符,是一个数字. Return the integer “file descriptor” that is used by the underlying implementation to request I/O operations from the operating system. This can be useful for other, lower level interfaces that use file descriptors, such as the fcntl module or os.read() and friends.
    f.isatty()如果文件是一个交互终端,则返回True,否则返回False。

 

其他
    f.close()
    f.flush(): Flush the internal buffer, like stdio‘s fflush. This may be a no-op on some file-like objects.
    f.truncate([size]) 截取文件,使文件的大小为size。

举例:
    打印当前文件目录 data文件夹下的所有文件

import os
procPath=os.getcwd()
dataPath=procPath+"/data"
files=[files for files in os.listdir(dataPath) ]  #if (files.find(timestamp) != -1)]
print files

 

    基本读写

#!/usr/bin/env python
# -*- coding: gb18030 -*-

poem='''\
Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!
'''

#1. write file
f=open('poem.txt', 'w') #open for 'w'riting
f.write(poem) #write text to file
f.close() #close the file

#2. read file
f=open('poem.txt') #if no mode is specified, 'r'ead mode is assumed by default

while True:
    line=f.readline()
    if len(line) == 0: #Zero length indicates EOF
        #此时line==""
        break
    print line, #notice comma to avoid automatic newline

f.close() #close the file

#3. append file
f=open('poem.txt','a')
f.write('hehe')
f.write("haha")
f.close()

    

    按行读写

#!/usr/bin/env python
# -*- coding: gb18030 -*-

'''
本文件说明:

    1. “list”遍历
        for ind in range(0,len(sample_list), 1):
            sample_list[ind]    #这样可以得到下标
            ...
        或
        for ele in sample_list
            ele	                #这样也行,但不能得到下标
            ...
        
    2. “Python类型判断”:  type(ele) is types.IntType 和 type(ele) == types.StringType是等价的——
        (1) type的返回值是一个"类",types.IntType也是一个"类"
        (2) is 比较的是是否指向同一个对象; == 比较的是类型的值

    3. “Python类型转换”:
         int(x [,base ])         将x转换为一个整数
         long(x [,base ])        将x转换为一个长整数
         float(x )               将x转换到一个浮点数
         complex(real [,imag ])  创建一个复数
         str(x )                 将对象 x 转换为字符串 ; 转为字符串也可以类似这样做 "%d" %int_var
         repr(x )                将对象 x 转换为表达式字符串
         eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象
         tuple(s )               将序列 s 转换为一个元组
         list(s )                将序列 s 转换为一个列表
         chr(x )                 将一个整数转换为一个字符
         unichr(x )              将一个整数转换为Unicode字符
         ord(x )                 将一个字符转换为它的整数值
         hex(x )                 将一个整数转换为一个十六进制字符串
         oct(x )                 将一个整数转换为一个八进制字符串
         
    4. 字符串变量 和 字符串常量 不同:
        字符串变量 在“拼接”时,需要加上“+”   i.e. str_var+"hehe"
        字符串常量 在“拼接”时,直接拼接      i.e. "sam""hehe"
        
    5. 按行写入文件
'''

import types

sample_list=['hehe',"Haha",3,"哈哈","Hey\\Hey","三木!"]
for ind in range(0,len(sample_list),1):
    if type(sample_list[ind]) is types.IntType:     #类型判断
        #sample_list[ind]=("%d\n" %sample_list[ind]) #int变量转字符串需要这样: "%d" %i
        sample_list[ind]=str(sample_list[ind])+"\n"  #字符串变量+字符串常量
    elif type(sample_list[ind]) is types.StringType:
        sample_list[ind]=(sample_list[ind]+"\n")    #字符串变量+字符串常量
    else:
        pass

#观察打印出list和list[i]的区别,体会print的功能
print
print sample_list
print sample_list[3]

#按行写入文件
f=open('myFile.txt','a')
f.writelines(sample_list)  #writelines(list)是不会自动加上换行符的
f.close()

    

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics