Python读书笔记-文件

好久没写了,回来继续。最近在看Python,记一下,要不以后用的时候,又忘记了。这次看的是Python的文件。

1、打开文件 open函数

help(open)

命令,可以看到open的信息

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)

可以看到,该函数执行会返回一个file类型的变量,是推荐的打开file方式。进一步查看 file.__doc__

mode种类有,‘r’(default)、’w’、’a’ 如果不存在,则会创建新的文件,’b’ 可以以二进制形式打开,’+’可允许同时读和写,’U’可以使python支持通用的回车符,但是‘U’不能和‘w’,’+’,共同使用。对于bufsize来将,0:无buff; 1:一行一行缓冲,再大,就是具体的bufsize了,

2、如果要从标准控制台读入流,可以使用 sys.stdin.read()

import sys
text=sys.stdin.read()
words=text.split()
print "Count:",len(words)

执行结果为

echo "This is a test" | python test3_stdin.py 
Count: 4

3、文件的关闭:close()

#Open a file
try:
    #Do Somthing
finally:
    file.close()

with语句可以自动关闭,需要引入 with_statement模块

from __future__ import with_statement

with open('somefile.txt') as somefile:
    do_something(somefile)

4、迭代文件内容:

import sys
import fileinput
filename=sys.argv[1]

print 'by bytes'
fileID=open(filename)
try:
	while True:
		buf=fileID.read(1)
		if buf:
			print buf,
		else:
			break;
finally:
	fileID.close()

print '\nby lines'
fileID=open(filename)
try:
	while(True):
		buf=fileID.readline()
		if buf:
			print buf,
		else:
			break
finally:
	fileID.close()

print '\nread all'
fileID=open(filename)
try:
	buf=fileID.read()
	print buf,
finally:
	fileID.close()

print '\nfileinput iterator'
for line in fileinput.input(filename):
	print line,

print '\nfile iterator'
fileID=open(filename)
try:
	for line in fileID:
		print line,
finally:
	fileID.close()

执行:

python test4_file.py test3_stdin.py 
by bytes
i m p o r t   s y s 
t e x t = s y s . s t d i n . r e a d ( ) 
w o r d s = t e x t . s p l i t ( ) 
p r i n t   " C o u n t : " , l e n ( w o r d s ) 

by lines
import sys
text=sys.stdin.read()
words=text.split()
print "Count:",len(words)

read all
import sys
text=sys.stdin.read()
words=text.split()
print "Count:",len(words)

fileinput iterator
import sys
text=sys.stdin.read()
words=text.split()
print "Count:",len(words)

file iterator
import sys
text=sys.stdin.read()
words=text.split()
print "Count:",len(words)

 

 

About: happyhls


发表评论

电子邮件地址不会被公开。 必填项已用*标注