关于文件

2018-05-05  本文已影响0人  梦亦殇灬
.1516630093403.png

打开文件

在python中可以利用open函数打开或者创建一个文件夹
f = open ("test.txt","w")

关闭文件

f = open ("test.txt","w")
f.close()

写入数据

这样写:如果原来test文件有内容 会被覆盖

f = open ("test.txt","w")
f.write("hellor world")
f.close()

如果这样写:如果原来test文件有内容就不会被覆盖 “世界, 你好”会被追加到文件末尾

f = open ("test.txt","a")
f.write("世界,你好")
f.close()

读取数据

读取一行:

f = open ("test.txt","r")
content = f.readline()
print(content)
f.close()

读取所有行:

f = open ("test.txt","r")
content = f.readlines()   #注意这里多了s
print(content)
f.close()

定位

获取当前定位:

f = open("test.txt", "r")
str = f.read(3)
print "读取的数据是 : ", str

# 查找当前位置
position = f.tell()
print "当前文件位置 : ", position
f.clse()

定位到某个位置:
用seek(offset, from)有2个参数

offset:偏移量
from:方向
0:表示文件开头
1:表示当前位置
2:表示文件末尾

f = open("test.txt", "r")
f.seek(5,0)
position = f.tell()
f.close()
上一篇 下一篇

猜你喜欢

热点阅读