>>> xxx = file('c:\\a.txt', 'r')
关键字的第一部分,是文件路径及名称。注意这里面,路径需要用\\
第二部分,是对文件的模式或者叫权限,一般有以下3种 "r" (read), "w" (write)和 "a"(append).
之后,就可以利用
xxx_content = infile.read()
xxx_content = infile.readlines()
来读取文件内容了
>>> xxx = file('c:\\a.txt', 'r')
>>> xxx_content = xxx.read()
>>> print xxx_content
This is line #1
This is line #2
This is line #3
END
>>> xxx.close()
>>>
>>> infile = file('c:\\a.txt', 'r')
>>> xxx = file('c:\\a.txt', 'r')
>>> for xxx_line in xxx.readlines():
print 'Line:', xxx_line
Line: This is line #1
Line: This is line #2
Line: This is line #3
Line: END
>>> xxx.close()
>>> xxx=file('c:\\test.txt','w')
>>> xxx.write('billrice')
>>> xxx.write('testtest')
>>> xxx.write('enter\n')
>>> xxx.writelines(['billrice','ricerice'])
>>> xxx.close()
>>>
>>> xxx=file('c:\\test.txt','r')
>>> content=xxx.read()
>>> print content
billricetesttestenter
billricericerice
>>>