实验4 文件应用编程
with open('data6_1.txt','r',encoding = 'utf-8') as f:
l = []
z = f.readlines()
for i in z:
p = []
i.strip()
p.append(i[0:5].strip())
p.append(i[5:8].strip())
p.append(int(i[8:11].strip()))
l.append(list(p))
y = lambda l: l[2]
l.sort(key = y,reverse=True)
n = open('data6_2.txt', 'w+')
count = 0
for i in l:
for u in i:
print(u,end = ' ')
n.writelines(str(u))
n.writelines(' ')
count = count + 1
if count %3 == 0:
print(end = '\n')
n.writelines('\n')


import random
n = input('输入随机抽点人数:')
m = set()
with open('data7.txt','r') as f:
f = f.readlines()
g = open('lucky.txt', 'w+')
while len(m) < int(n):
x = random.randint(0,len(f) - 1)
y = f[x]
y.strip()
m.add(y)
g.writelines(y.strip())
g.writelines('\n')
print(y.strip())


import random
import datetime
t = datetime.datetime.now()
t.strftime('%Y%m%d')
t = str(t)[0:4]+str(t)[5:7]+str(t)[8:10]
k = t + '.txt'
n = input('输入随机抽点人数:')
m = set()
with open('data7.txt','r') as f:
f = f.readlines()
g = open( k,'w+')
while len(m) < int(n):
x = random.randint(0,len(f) - 1)
y = f[x]
y.strip()
m.add(y)
g.writelines(y.strip())
g.writelines('\n')
print(y.strip())


实验总结:
1.使用line.strip('\n') == ' '来处理空白行,适用于空白行只有\n的情形。
2.使用writelines()函数向文件中写入多行数据时,不会自动给各行添加换行符。
3.readline()函数在读取文件中一行内容时,会读取最后的换行符“\n”,再加上print()函数输出内容时会默认换行,所以输出结果中会看到多出了一个空行。

浙公网安备 33010602011771号