Python read和write方法

Python read和write方法:

read():

从文件中读取字符串

注:Python 字符串可以是二进制数据,而不仅仅是文字。

语法:

文件对象.read([count])

count:打开文件需要读取的字符数

注:read 函数不使用 count 会尽可能多地读取更多的内容,通常一直读取到文件末尾。

程序:

# 打开创建好的 test.txt 文件
f = open("test.txt",'r')
# 输出文件所有的内容
print(f.read())
# 关闭文件
f.close()
# hello,world.
# hello,world2.
# hello,world3.
# hello,world4.
# hello,world5.
# hello,world6.
# hello,world7.
# hello,world8.
# hello,world9.



# 使用 count
# 打开创建好的 test.txt 文件
f = open("test.txt",'r')
# 输出文件的前 11 个字符
print(f.read(11))
# ['hello,world.\n']
# 关闭文件
f.close()
# hello,world

文件位置:

tell():

返回文件内当前指向的位置

# 使用 count
# 打开创建好的 test.txt 文件
f = open("test.txt",'r')
# 输出文件的前 11 个字符
print(f.read(11))
# 返回文件内当前指向的位置
print(f.tell())
# 11
# 关闭文件
f.close()
# hello,world

seek(offset [,from]):

改变当前文件的位置

  offset:表示要移动的字节数

  from :指定开始移动字节的参考位置。

    0:文件开头

    1:当前位置

    2:文件末尾

程序:

# 打开创建好的 test.txt 文件
f = open("test.txt",'r')
# 输出文件的前 11 个字符
print(f.read(11))
# hello,world
# 返回文件内当前指向的位置
print(f.tell())
# 11
print(f.seek(0,0))
# 0
print(f.tell())
# 0
print(f.read(11))
# hello,world
# 关闭文件
f.close()

write( ):

将任意字符串写入一个文件中

注:Python字符串可以是二进制数据 和 文字,换行符('\n') 需要自己添加

语法:

文件对象.write(字符串)

程序:

# write 方法
# 打开创建好的 test.txt 文件

f = open("test.txt",'w')
# 在开头,添加文件内容
f.write('hey boy')

# 关闭文件
f.close()

2020-02-14

猜你喜欢

转载自www.cnblogs.com/hany-postq473111315/p/12303304.html