python文件操作举例

2023-01-31 02:01:43 操作 文件 举例

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


相关文章