标签:python
1.文件的操作:
|
操作 |
解释 |
|
output=open(r‘c:\123.txt‘,‘w‘) |
创建输出文件,w写入 |
|
input=open(‘data‘,‘r‘) |
创建输出文件,r读取 |
|
input=open(‘data‘) |
创建输出文件,r默认 |
|
s=input.read() |
整个文件读取单一字符串 |
|
s=input.read(N) |
读取之后的n个字节到字符串 |
|
s=input.readline() |
读取下一行到一个字符串 |
|
alist=input.readlines() |
读取整个文件到字符串列表 |
|
output.write(s) |
写入字节字符串到文件 |
|
output.writelines(list) |
把列表内所有字符串写入文件 |
|
output.close() |
手动关闭 |
|
output.flust() |
清空缓存 |
|
anyFile.seek(N) |
查询 |
|
for line in open(‘data‘):use line |
逐行读取 |
|
open(‘f.txt‘,encodeing=‘latin-1‘) |
设置unicode |
|
open(‘f.bin‘,‘rb‘) |
|
2.基本操作实例
>>> myfile=open('123.txt','w')
>>> myfile.write
<built-in method write of _io.TextIOWrapper object at 0x012D8D30>
>>> myfile.write('hello world \n')
13
>>> myfile.write('hello world 2 \n')
15
>>> myfile.close ()
>>> myfile=open('123.txt')
>>> myfile.readline
<built-in method readline of _io.TextIOWrapper object at 0x0170B5B0>
>>> myfile.readline ()
'hello world \n'
>>> myfile.readline ()
'hello world 2 \n'
>>> myfile.readline ()
''
>>>
上面是读取、写入文件
3.只有字符串才能够写入文件
>>> myfile=open('123.txt','w')
>>> l=(1,2,3)
>>> myfile.write(l)
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
myfile.write(l)
TypeError: must be str, not tuple
>>> >>> t=[1,2,3]
>>> myfile.write(t)
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
myfile.write(t)
TypeError: must be str, not list
>>>
就说到这里,谢谢大家
------------------------------------------------------------------
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:python
原文地址:http://blog.csdn.net/raylee2007/article/details/48093153