python文件流习题解析

def read_data():
try:

    l1=[]
    f=open('info.txt', 'r')
    l=f.readlines()
    f.close()
    for line in l:
        s=line.strip()
        name, age, score=s.split(' ')
        age=int(age)
        score=int(score)
        l1.append({'name': name, 'age': age, 'score': score})
except OSError:
    print('读取文件失败')
return l1

l=read_data()
def save_data(l):
try:
f=open(‘info.txt’, ‘a’)
for i in l:
f.write(i[‘name’])
f.write(’ ’ + str(i[‘age’]))
f.write(’ ’ + str(i[‘score’]) + ‘\n’)
f.close()
except OSError:
print(‘打开失败’)
save_data(l)

def input_data():
l=[]
while True:
s=input()
if not s:
break
l.append(s)

return l

def save_data_file(file=’test.txt’):
try:
f=open(file, ‘w’)
for i in input_data():
f.write(i + ‘\n’)
f.close()
except OSError:
print(‘文件打开失败’)

def read_data_file(file=’test.txt’):
try:
l=[]
f=open(file, ‘r’)
for j in f:
j=j.rstrip()
l.append(j)
f.close()
l1=enumerate(l, start=1)
for i in l1:

        print('行号', i[0], i[1])

except OSError:
    print('文件打开失败')

read_data_file()

猜你喜欢

转载自blog.csdn.net/weixin_32759777/article/details/81952124