前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python文件操作举例

python文件操作举例

作者头像
py3study
发布2020-01-10 17:10:46
4890
发布2020-01-10 17:10:46
举报
文章被收录于专栏:python3python3

1.把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中

import codecs

def paixu(l):

for i in xrange(0,len(l)-1):

for j in xrange(0,len(l)-i-1):

if l[j]>l[j+1]:

               l[j],l[j+1] = l[j+1],l[j]

return l

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)

with codecs.open("paixu.txt","w") as file1:

for i in list1:

           file1.write(str(i))

           file1.write("\n")

       file1.close()

with codecs.open("paixu.txt","r") as file2:

       list2 = file2.readlines()

print("read data: ")

print(list2)

       file2.close()

with codecs.open("paixu.txt","a") as file3:

       list3 = sorted(list2,reverse=True)

for j in list3:

           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)字符串

import codecs

str1= raw_input("please input a string: ")

with codecs.open("example.txt","w") as file1:

   file1.write(str1)

   file1.close()

运行:please input a string: huangzhenping

结果:huangzhenping

# 2)列表和元组

import codecs

list2 = list(raw_input("please input a list: "))

with codecs.open("example.txt","w") as file2:

for i in list2:

       file2.write(str(i))

   file2.close()

运行:please input a list: a,b,c,1,2,3

结果:a,b,c,1,2,3

# 3)字典

import codecs

dict1 = dict(name="hzp",sex="male",age="27")

with codecs.open("example.txt","w") as file3:

for x,y in dict1.iteritems():

       file3.write(str(x) + ":" + str(y) + "\n")

   file3.close()

结果:

age:27

name:hzp

sex:male

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档