自学Python-文件

文件

open()

1
2
3
4
5
6
7
8
f = open("test.txt","w+")
f.write("This is a file")
f.close()

f = open("test.txt","r")
for i in f:
print i
f.close()

open()函数需要两个参数,第一个参数时文件名,第二个是打开方式,打开方式有以下类型:

模式 描述
r 以读方式打开文件,可读取文件信息。
w 以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容
a 以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建
r+ 以读写方式打开文件,可读写文件信息。
w+ 清除文件内容,然后以读写方式打开文件。
a+ 以读写方式打开文件,指针指向文件末尾。
b 以二进制打开文件,只对windows和Dos有效。

read()、readline()、readlines()

read()

read()函数如果指定了size参数就读取size长度,否则读取全文。

1
2
3
4
5
6
7
8
9
f = open("test.txt","r")
txt = f.read()
print txt
f.close()
#输出:
#This is a file
#Hello World!
#I am Carl
#

readline()

readline()函数的size参数含义和read()一样,此函数是以行为单位,如果不指定长度每次读取一行

1
2
3
4
5
6
7
8
f = open("test.txt","r")
txt = f.readline()
print txt
#This is a file
txt = f.readline()
print txt
#Hello World!
f.close()

readlines()

readlines()返回的是以行为单位的列表

1
2
3
4
5
f = open("test.txt","r")
txt = f.readlines()
print txt
f.close()
#输出:['This is a file\n', 'Hello World!\n', 'I am Carl\n']

seek()

seek()函数是用来控制文件指针以字节为单位进行移动的
seek()函数有两个参数offset、whence:

  • offset:移动的字节数
  • whence:可选参数,默认值是0代表从文件头向后移动,1是从当前位置向后移动,2是相对文件尾移动
1
2
3
4
5
6
7
8
9
10
11
f = open("test.txt","r")
txt = f.readline()
print txt
#This is a file
f.seek(0)
txt = f.readline()
print txt
#This is a file
print f.tell()
#15
f.close()

tell()函数是获取当前指针位置
最后操作完文件记得使用close()函数进行关闭


自学Python-文件
https://carl-5535.github.io/2020/11/10/自学python/自学Python-文件/
作者
Carl Chen
发布于
2020年11月10日
许可协议