- 把一個(gè)數(shù)字的list從小到大排序饱岸,然后寫入文件,然后從文件中讀取出來文件內(nèi)容徽千,然后反序苫费,在追加到文件的下一行中
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)
- 分別把 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)))
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者