一、文件和文件夹
文件:文本文件、二进制文件
文件夹:
(Windows)C:\python\nihao.txt
(Mac/Linux) /home/python/nihao.txt
跨平台路径:os.path.abspath(path)
查看属性:os.stat(filename)
例如:
>>> p1 = 'c:\\python\\nihao.txt'
>>> import os
>>> os.stat(p1)
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0L,
st_nlink=0, st_uid=0, st_gid=0, st_size=10L,
st_atime=1466563098L, st_mtime=1466563113L, st_ctime=1466563098L)
二、读、写文件
文件的特点:
>>> 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']
其中,‘_ _ iter_ _’说明这种类型是可迭代的,可以使用for循环、Iter()…next()、迭代器
打开文件(读文件):
>>> f = open(p1)
>>> for i in f: #前提当文件可读时,该语句才该正常执行
... print i
...
learn python
xiaoxu
当再次输出文件的内容,此时没有结果输出,说明此时,指针已经处于文件内容的末尾,代码如下:
>>> f = open(p1)
>>> for i in f:
... print i
...
learn python
xiaoxu
>>> for i in f:
... print i
...
>>>
>>>
创建文件:
以“w”的模式打开文件,原来的内容将会被清空,保存新输入的内容,例如:
>>> fp = open("c:\\python\\nihao.txt","w")
>>> fp.write("My name is Xiaoxu")
>>> fp.close()
>>> f = open("c:\\python\\nihao")
>>> f = open("c:\\python\\nihao.txt")
>>> for i in f:
... print i
...
My name is Xiaoxu.
>>>
以“a”的模式打开文件,会原来的内容末尾继续追加新的内容,例如:
>>> fp = open("c:\\python\\niaho.txt","a")
>>> fp.write("I love Python")
>>> fp.close()
>>> fp = open("c:\\python\\nihao.txt","a")
>>> fp.write("I love Python")
>>> fp.close()
>>> f = open("c:\\python\\nihao.txt")
>>> for i in f:
... print i
...
My name is Xiaoxu.I love Python
注意:在每次打开文件后,记住最后一步一定要关闭文件,即使用如上代码所示的fp.close()
在处理文件的打开与关闭时,有可能会忘记关闭文件这一操作,还有一种写法,可以不需要考虑关闭这一操作,即使用with语句解决。例如:
>>> with open("c:\\python\\nihao.txt","a") as fp:
... fp.write("\nCanglaoshi is a good teacher.") #其中\n代表换行
...
>>> f = open("c:\\python\\nihao.txt")
>>> for i in f:
... print i
...
My name is XiaoxuI love Python
Canglaoshi is a good teacher.
>>>
三、文件不同的读取方法
read()
readline()
readlines()
import fileinput
read()的用法:
>>> help(file.read)
Help on method_descriptor:
read(...)
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
>>>
其中,read([size])中的size是可选的,返回size字节的字符串。
read一次性把文件内容读入内容,缺点是当文件内容太多时,就存不下。
>>> f = open("c:\\python\\nihao.txt")
>>> c = f.read()
>>> c
'My name is Xiaoxu. I love Python\nCanglaoshi is a good teacher.'
>>> f = open("c:\\python\\nihao.txt")
>>> c = f.read(10)
>>> c
'My name is'
>>>
readline()的用法:
>>> help(file.readline)
Help on method_descriptor:
readline(...)
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
>>>
readline():’size’它是以一行为单位,返回字符串,不是以字节为单位的,也就是每次读一行,一次往下循环。若不对’size’这个可选参数进行限制,它就读到最后一个
>>> f = open("c:\\python\\nihao.txt")
>>> f.readline()
'My name is Xiaoxu. I love Python\n'
>>>
readlines()的用法:
>>> help(file.readlines)
Help on method_descriptor:
readlines(...)
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
>>>
它返回的是一行为单位的列表。
举例如下:
>>> f = open("c:\\python\\nihao.txt")
>>> c = f.readlines()
>>> c
['My name is Xiaoxu. I love Python\n', 'Canglaoshi is a good teacher.']
>>>
import fileinput的用法
有时,会遇到大的文件,由于read()和readlines()一次性把文件内容读入内存,对大文件的内容不适用,所以可以采用readline()或者fileinput模块。其中,readline()是一行一行读取内容的。
举例如下:
>>> import fileinput
>>> for i in fileinput.input(r'c:\python\nihao.txt'):
... print i
...
My name is Xiaoxu. I love Python
Canglaoshi is a good teacher.
>>>
seek()的用法:
>>> help(file.seek)
Help on method_descriptor:
seek(...)
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
>>>
当读文件内容读到文件末尾后,指针指到了文件末尾,若要使指针放在文件开头,除了重新打开文件还可以采用下面的方法:
>>> f = open(r'c:\python\nihao.txt')
>>> for i in f:
... print i
...
My name is Xiaoxu. I love Python
Canglaoshi is a good teacher.
>>> f.seek(0) #此操作可以把指针移到文件内容的开头,与重新打开文件时的一样
>>> for i in f:
... print i
...
My name is Xiaoxu. I love Python
Canglaoshi is a good teacher.
>>>
tell()的用法:
tell()可以判断指针的位置,例如:
>>> f.seek(0)
>>> for i in f:
... print i
...
My name is Xiaoxu. I love Python
Canglaoshi is a good teacher.
>>> f.seek(4)
>>> f.tell()
4L
>>> f.readline()
'ame is Xiaoxu. I love Python\n'
>>>