一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python中文件读写的例子

时间:2016-10-07 编辑:简简单单 来源:一聚教程网


print关键字用来将后面的内容输出到屏幕

str = "I love Python"
>>> print str
I love Python
>>> sum = lambda arg1,arg2: arg1 + arg2
>>> print '1 + 2 = %d' %sum(1,2)
1 + 2 = 3
input(), raw_input()

这两个函数都是从命令行读取字符串,前者将读取到的字符串按照Python的语法解析并返回,后者将读到的字符串只是当作字符串处理

>>> raw_input("CMD:")
CMD:1+2
'1+2'
>>> input("CMD:")
CMD:1+2
3
open()

file object = open(file_name [, access_mode][, buffering])
#file_name: a string value
#access_mode: read, write, append, etc.
    #r  reading only
    #rb reading only in binary format.
    #r+ reading and writing.
    #rb+ reading and writing in binary format.
    #w  writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
    #wb writing only in binary format. ...
    #w+ writing and reading. ...
    #wb+ writing and reading in binary format. ...
    #a  Oappending. ...
    #ab appending in binary format. ...
    #a+ Oappending and reading. ...
    #ab+ appending and reading in binary format. ...
#buffering:
    #0, no buffering takes place.
    #1, line buffering is performed while accessing a file.
    #an integer greater than 1, then buffering action is performed with the indicated buffer size.
    #negative, the buffer size is the system default(default behavior).
fileObject attributes

fo.closed

Returns true if file is closed, false otherwise.

fo.mode

Returns access mode with which file was opened.

fo.name

Returns name of the file.

fo.softspace

Returns false if space explicitly required with print, true otherwise.

fileObject methods

fo.close()

将未写入的数据写入文件并关闭文件对象

fo.write()

向文件对象中写入字符串

fo.tell()

Returns the position of file

fo.seek(offset,[, from])

移动文件位置指针

0表示从文件开头

1表示从当前位置

2表示从文件结尾

os module

os.rename(cur_file_name, new_file_name)

重命名文件##os.remove(file_name)

删除文件

os.mkdir("newdir")

创建新的文件夹

os.chdir("objdir")

切换工作目录

os.getcwd()

显示当前工作目录

os.rmdir()

删除文件夹

 写模式和追加模式

写模式和追加模式下打开的文件如果不存在,该文件会默认被创建,其内容为空。

(1) r mode: write to a file

$ cat file_w.py
filename = "temp.txt"
f = open(filename,"w")
f.write("hello, world.\n")
f.write("hi, python!\n")
f.close()
$ python file_w.py
$ cat temp.txt
hello, world.
hi, python!
(2) r mode: write to the same file again
$ cat file_w.py
filename = "temp.txt"
f = open(filename,"w")
f.write("Be serious!\n")
f.write("Not funny at all!\n")
f.close()
$ python file_w.py
$ cat temp.txt
Be serious!
Not funny at all!
可以看出,之前文件中的内容都被清空了。
(3) a mode: write to the same file

$ cat file_a.py
filename = "temp.txt"
f = open(filename,"a")
f.write("hello, world.\n")
f.write("hi, python!\n")
f.close()
$ python file_a.py
$ cat temp.txt
Be serious!
Not funny at all!
hello, world.
hi, python!
2.2 读模式
对于读模式下打开的文件,可以进行读取操作。如果读取模式下打开一个不存在的文件,会报错(IOError: [Errno 2] No such file or directory)。

(1) read

像上文中说的read默认读取整个文件的内容并返回。

$ cat file_r.py
filename = "temp.txt"
f = open(filename,"r")
print f.read()
f.close()
$ python file_r.py
Be serious!
Not funny at all!
hello, world.
hi, python!
(2) 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.
读取文件的一行,保留换行符,到文件末尾返回空串。
$ cat file_readline.py
filename = "temp.txt"
f = open(filename,"r")
line =  f.readline()
while line://最后的空行也会被打印出来
  #readline will retain an enter, so add ',' at the end to remove the enter of print
  print line,
  line = f.readline()
f.close()
$ cat temp.txt
Be serious!
Not funny at all!
hello, world.
hi, python!
//这里有一个空行
$ python file_readline.py
Be serious!
Not funny at all!
hello, world.
hi, python!
//这里最后也会打出空行
(3) 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.
重复调用readline读取文件中的所有行到一个list。
$ cat file_readlines.py
filename = "temp.txt"
f = open(filename,"r")
lines =  f.readlines()
for line in lines:
  print line,
f.close()
$ cat temp.txt
Be serious!
Not funny at all!
hello, world.
hi, python!
//这里有一个空行
$ python file_readlines.py
Be serious!
Not funny at all!
hello, world.
hi, python!
//这里最后也会打出空行
好了,到这里就可以用python进行文件的基本操作了,后面有复杂的需求会进一步补充

热门栏目