1.文件的读取

1
2
3
4
5
6
f = open('D:/python/Android.txt')
txt = f.read()
print(txt)
-------------------
这是一个文件而已,测试python文件读取的文件
年少的时候,情窦初开,大家都很容易对班级里的某个女生或某个男生情愫暗生

1.1 读取n个字符

1
2
3
4
5
f1 = open('D:/python/Android.txt')
txt1 = f1.read(10)
print(txt1)
-----------
这是一个文件而已,测

1.2 tell()当前文件指针的位置

1
2
num = f1.tell()
print(num) # 20 (这是一个文件而已,测) 一个汉字2个字符加一个中文符号的两个字符

1.3 文件指针的移动 seek(offset,from)

offset:字符偏移量 from:0 文件起始位置; from:1 当前位置;from:2 文件末尾

1
2
3
4
f = open('D:/python/Android.txt')
f.seek(20,0)#从文件的第20个字符开始读取
start = f.readline()
print(start) #试python文件读取的文件

1.4 文件转化为list

print(list(f))

1.5 循环读取文件每一行

1
2
3
f = open('D:/python/Android.txt')
for each in f:
print(each)

2.文件的写入

从文件Android.txt中读取写如到text.txt文件中

1
2
3
4
5
f = open('D:/python/Android.txt')
f1 = open('D:/python/text.txt','w') # w 允许写入
for each in f:
f1.write(each)
f1.close()

A,B有一段对话,读取对话内容,把A的对话保存在A.txt中;把B的对话保存在B.txt中
对话内容如:talk.txt
A:你吃了吗?
B:没有,你呢?
A:我也没吃
B:那一起去吃饭吧!
A:好啊!
B:吃什么呢?
A:吃羊肉剁荞面吧
B:好啊!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def readWrite(filePath):
f = open(filePath)
a = []
b = []
for each in f:
(role,content) = each.split(':',1)
if role == 'A':
a.append(content)
if role == 'B':
b.append(content)
file_name_a = 'D:/python/A.txt'
file_name_b = 'D:/python/B.txt'
file_a = open(file_name_a,'w')
file_b = open(file_name_b,'w')
file_a.writelines(a)
file_b.writelines(b)
file_a.close()
file_b.close()
readWrite('D:/python/talk.txt')

读写完成后:A.txt
你吃了吗?
我也没吃
好啊!
吃羊肉剁荞面吧
B.txt
没有,你呢?
那一起去吃饭吧!
吃什么呢?
好啊!