文件操作和流概念在许多语言中都是通行的,如果学习python之前会C++或者java这些静态语言,那么里面很多细节就不必用太多功夫探究了。
#!/user/bin/evn python
#coding:utf-8
from _codecs import decode
print 'python文件读写操作'
#标准输入输出流
str = raw_input('请输入字符\n')
print str
str1 = input('请输入表达式\n')
print str1
print '======================================'
#打开文件
file = open('D:\python\demo9.txt')
print file.name
print decode(file.readline(),'GBK')
print file.closed
print file.encoding
'''文件打开模式:默认r
'''
print file.mode
file.close()
print '======================================='
#用w+模式打开文件读写,缓冲区1024,如果为-1则使用系统默认,0为不适用,1为行缓冲,
#写入默认coding:utf-8,亦可使用encoding关键字参数指定
file2 = open('D:\python\demo9-1.txt','w+',1024)
file2.write('python\n')
file2.writelines('python你好\n')
file2.writelines('python\n')
#刷新缓冲区
file2.flush()
file2.close()
file2 = open('D:\python\demo9-1.txt')
#读取10个字符,无参则为全部读取
print file2.read(2)
print decode(file2.readline(),'UTF-8')
#读取多行,注意每次读取指针都会指向next,上面的read已经造成next
for string in file2.readlines():
print string
print '======================================='
print '当前指针位置',file2.tell()
#将指针归零,第一个参数为移动的字节数,第二个是参考位置,默认0即文件开头,1为当前位置,2为文件末尾
file2.seek(0,0)
print file2.readline()
输出:
python文件读写操作
请输入字符
python
python
请输入表达式
'PYTHON'.lower()
python
======================================
D:\python\demo9.txt
用python打开文件
False
None
r
=======================================
py
thon
python你好
python
=======================================
当前指针位置 30
python