Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
1
2
3
4
5
6
7
8
9
10
11
12
可以看到,print的参数为以下几项:
with open("data.txt") as f:
print(f.read())
1
2
Line one: Hello World!
Line two: Hello World!
Line three: Hello World!
Line four: Hello World!
1
2
3
4
f.readline
f.readline用于读取文件中的一行。
with open("data.txt") as f:
print(f.readline())
1
2
Line one: Hello World!
1
f.readlines
f.readline用于读取文件中所有行。默认返回为所有行构成的list。
with open("data.txt") as f:
for line in f:
print(line, end='')
1
2
3
Line one: Hello World!
Line two: Hello World!
Line three: Hello World!
Line four: Hello World!
1
2
3
4
写文件
f.write
f.write用于将字符串写入到文件中,返回写入的字节数。
with open("data.txt", "w") as f:
print(f.write("Hello World!"))
1
2
12
1
其他文件操作
f.tell
f.tell用于返回文件指针当前的位置(距离文件起始位置的字节数)
with open("data.txt", "r") as f:
f.read(5)
print(f.tell())
1
2
3
5
1
f.seek
f.seek用于移动文件指针到指定的位置。用法如下:
seek(cookie, whence=0, /) method of _io.TextIOWrapper instance
Change stream position.
Change the stream position to the given byte offset. The offset is
interpreted relative to the position indicated by whence. Values
for whence are:
* 0 -- start of stream (the default); offset should be zero or positive
* 1 -- current stream position; offset may be negative
* 2 -- end of stream; offset is usually negative
1
2
3
4
5
6
7
8
9
10
它有两个参数,第一个是偏移量cookie,第二个是起始位置whence。起始位置可以是文件起始位置(0)、当前位置(1), 文件尾(2)。
例子如下: