一、读文件
1. open函数
2. with … as …
这种读取文件的方法更加合理,因为不需要考虑打开的文件是否关闭。
3. read的方法
# 1. Read certain amount of characters
with open(example1, "r") as file1:
print(file1.read(16))
print(file1.read(5))
print(file1.read(9))
# 2. Read one line
with open(example1, "r") as file1:
print("first line: " + file1.readline())
# 3. Iterate through the lines
with open(example1,"r") as file1:
i = 0
for line in file1:
print("Iteration", str(i), ": ", line)
i = i + 1
# 4. Read all lines and save as a list
with open(example1, "r") as file1:
FileasList = file1.readlines()
二、写文件
写和读的没有差别,我们重点介绍下读写的模式。
- r+ : Reading and writing. Maybe useful to add a
.truncate()
method at the end of your data. - w+ : Writing and reading.
- a+ : Appending and Reading.
在同时读写文件中,游标的概念很重要。write是直接在new file头开始写,而append是在打开文件的尾巴开始写。read是从当前游标开始向后读。
控制游标的函数:
.tell()
- returns the current position in bytes 返回当前游标位置.seek(offset,from)
- changes the position by ‘offset’ bytes with respect to ‘from’. From can take the value of 0,1,2 corresponding to beginning, relative to current position and end
举例一下就知道怎么回事了:
with open('Example2.txt', 'a+') as testwritefile:
print("Initial Location: {}".format(testwritefile.tell()))
data = testwritefile.read()
if (not data): #empty strings return false in python
print('Read nothing')
else:
print(testwritefile.read())
testwritefile.seek(0,0) # move 0 bytes from beginning.
print("\nNew Location : {}".format(testwritefile.tell()))
data = testwritefile.read()
if (not data):
print('Read nothing')
else:
print(data)
print("Location after read: {}".format(testwritefile.tell()) )
output:
Initial Location: 70
Read nothing
New Location : 0
Overwrite
This is line C
This is line D
This is line E
This is line E
Location after read: 70