Python练习2

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


def str2int(string):
    return int(string)


num_list = [45, 2, 34, 65, 653, 2435, 1, 4, 234]
num_list.sort()
print num_list
num_str = ' '.join(map(int2str, num_list))
with open('num_list.txt', 'wb') as f:
    f.write(num_str)

with open('num_list.txt', 'rb') as f:
    new_list = map(str2int, f.read().split())

new_list.reverse()
print new_list
new_str = ' '.join(map(int2str, new_list))

with open('num_list.txt', 'ab') as f:
    f.write('\n' + new_str)
执行结果1
  1. 分别把 string, list, tuple, dict写入到文件中
f_str = 'hello'
f_list = ['alex', 'hello', 'javier']
f_tup = ('hi', 'python',)
f_dict = {'name': 'javier', 'age': 18}

with open('text2.txt', 'wb') as f:
    f.write('string:{string}\nlist:{list}\ntuple:{tuple}\ndict:{dict}\n'.format(string=f_str, list=str(f_list), tuple=str(f_tup), dict=str(f_dict)))
执行结果2

推荐阅读更多精彩内容