1.把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
importcodecs
defpaixu(l):
foriinxrange(0,len(l)-1):
forjinxrange(0,len(l)-i-1):
ifl[j]>l[j+1]:
l[j],l[j+1] = l[j+1],l[j]
returnl
if__name__ =="__main__":
new_list=list(input("please input a list,like( 1,2,3): "))
print("oringin date: ")
print(new_list)
list1 = paixu(new_list)
print("sorted: ")
print(list1)
withcodecs.open("paixu.txt","w")asfile1:
foriinlist1:
file1.write(str(i))
file1.write("\n")
file1.close()
withcodecs.open("paixu.txt","r")asfile2:
list2 = file2.readlines()
print("read data: ")
print(list2)
file2.close()
withcodecs.open("paixu.txt","a")asfile3:
list3 =sorted(list2,reverse=True)
forjinlist3:
file3.write(str(j))
print("reversed : ")
print(list3)
file3.close()
结果:
please input a list,like( 1,2,3): 1,3,5,7,9,0,2,4,6,8
oringin date:
[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]
sorted:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
read data:
['0\n', '1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9\n']
reversed :
['9\n', '8\n', '7\n', '6\n', '5\n', '4\n', '3\n', '2\n', '1\n', '0\n']
2.分别把 string, list, tuple, dict写入到文件中
# 1)字符串
importcodecs
str1=raw_input("please input a string: ")
withcodecs.open("example.txt","w")asfile1:
file1.write(str1)
file1.close()
运行:please input a string: huangzhenping
结果:huangzhenping
# 2)列表和元组
importcodecs
list2 =list(raw_input("please input a list: "))
withcodecs.open("example.txt","w")asfile2:
foriinlist2:
file2.write(str(i))
file2.close()
运行:please input a list: a,b,c,1,2,3
结果:a,b,c,1,2,3
# 3)字典
importcodecs
dict1 =dict(name="hzp",sex="male",age="27")
withcodecs.open("example.txt","w")asfile3:
forx,yindict1.iteritems():
file3.write(str(x) +":"+str(y) +"\n")
file3.close()
结果:
age:27
name:hzp
sex:male