Python编程—操作文件

操作文件
1、open API介绍
Help on built-in function open in module __builtin__:

open(…)
open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object.  This is the
preferred way to open a file.  See file.__doc__ for further information.
(END)
2、打开文件
andy@andy-virtual-machine:~/python_test$ cat example.py
#! /usr/bin/python
#coding:utf-8
#test open api to open a file

fd=open(“1.txt”)
print type(fd)
andy@andy-virtual-machine:~/python_test$ ./example.py
<type ‘file’>
andy@andy-virtual-machine:~/python_test$

Python语言打开文件模式
模式 描述
r 以读方式打开文件,可读取文件信息。
w 以写方式打开文件,可向文件写入信息。若文件存在,则清空该文件,再写入新内容。
a 以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建。
r+ 以读写方式打开文件,可对文件进行读和写操作。
w+ 消除文件内容,然后以读写方式打开文件。
a+ 以读写方式打开文件,并把文件指针移到文件尾。
b 以二进制模式打开文件,而不是以文本模式。
%title插图%num3、读文件中内容
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.

andy@andy-virtual-machine:~/python_test$ cat example.py
#! /usr/bin/python
#coding:utf-8
#test open api to open a file

fd=open(“1.txt”)
print type(fd)
content=fd.read()
print content
andy@andy-virtual-machine:~/python_test$

4、查看文件状态%title插图%num
Help on built-in function localtime in module time:

localtime(…)
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time.
When ‘seconds’ is not passed in, convert the current time instead.
(END)
andy@andy-virtual-machine:~/python_test$ cat example.py
#! /usr/bin/python
#coding:utf-8
#test open api to open a file
import os
import time

fd=os.stat(“1.txt”)
print type(fd)
print fd
print fd.st_ctime
print fd.st_ctime
print time.localtime(fd.st_ctime)%title插图%num