Python入门到精通

Python基础015--文件对象的读写操作

2018-02-27  本文已影响1人  不一样的丶我们

文件对象的读写操作

# 第一种读写文件的方式,不常使用了
# 文件打开之后必须要有关闭文件的操作
In [1]: f = open('./test.txt','r+')
In [2]: f.read()                
Out[2]: '#coding=utf-8\n\nthis is a file\naaaaaaa\nbbbbbbb\nccccccc\niiabcdedfabcdefgi\n'
In [22]: f.read(10)
Out[22]: '#coding=ut'
In [3]: f.write('python')
In [5]: f.seek(0,0)             # 重新指向文件的头部
In [6]: f.read()
Out[6]: '#coding=utf-8\n\nthis is a file\naaaaaaa\nbbbbbbb\nccccccc\niiabcdedfabcdefgi\npython'
In [7]: f.seek(0,0)
In [8]: f.readline()            # 从文件中读写并返回一行  一般模式下是一行一行的读取,换行符单独算一行
Out[8]: '#coding=utf-8\n'
In [9]: f.readlines(2)          # 读取文件所有的行为作为一个列表返回
Out[9]: 
['\n',
 'this is a file\n',
 'aaaaaaa\n',
 'bbbbbbb\n',
 'ccccccc\n',
 'iiabcdedfabcdefgi\n',
 'python']
In [10]: f.mode                 # 文件打开时的访问方式
Out[10]: 'r+'
In [11]: f.name                 
Out[11]: './test.txt'
In [12]: f.close()
 
# 把列表或者字典写入到文件中
In [1]: list1 = ['apple','python']
In [2]: file1 = open('./ccc.txt','w+')
In [3]: file1.write(str(list1))
In [4]: file1.tell()
Out[4]: 19
In [5]: file1.seek(0)
In [6]: file1.read()
Out[6]: "['apple', 'python']"

# 把一个文件的内容写入到另一个文件中
with open('file1.txt','r') as f1:
    with open('file2.txt','w') as f2:
        f2.write(f1.read())
 
# 第二种读写文件的方式,经常使用
# 文件打开之后不必执行关闭的操作
In [27]: with open('./test.txt', 'r+') as e:
    ...:     line = e.read(20)
    ...:     lines = e.readlines()
    ...:     write = e.write('python')
    ...:     

In [28]: print line
#coding=utf-8
this 
In [29]: print lines
['is a file\n', 'aaaaaaa\n', 'bbbbbbb\n', 'ccccccc\n', 'iiabcdedfabcdefgi\n', 'python']

上一篇 下一篇

猜你喜欢

热点阅读