python 基础 3.2 文件 for 练习
2024-09-06 06:50:30
#/usr/bin/python
#coding=utf-8
#@Time :2017/11/1 22:19
#@Auther :liuzhenchuan
#@File :1030-1031练习题.py
###1 把一个数字的list从小到大排序,然后写到文件中,然后从文件中读取文件内容然后反序,在追加到文件的
#下一行中
###2 分别把string list tuple dict 写到文件中
import codecs
l1 = [51,34,67,8,10,11,9]
l1.sort()
l2 = str(l1)
print l2
with open('a.txt','w+') as fd:
for i in l2:
fd.write(str(i))
fd.write('\n')
fd.close()
#打印出文件内容
with open('a.txt') as fd:
print fd.read(),
#反序追加到文件的下一行中
l1.reverse()
l3 = str(l1)
with open('a.txt','a') as fd:
for j in l3:
fd.write(str(j))
# fd.write('\n')
fd.close()
#打印出文件内容
with open('a.txt') as fd:
print fd.read()
>>> [8, 9, 10, 11, 34, 51, 67]
[67, 51, 34, 11, 10, 9, 8]
[67, 51, 34, 11, 10, 9, 8]
####2 分别把string list tuple dict 写到文件中去
#把字符串写到文件中去
str1 = 'abcde'
with open('b.txt','w+') as f:
f.write(' '.join(str1))
with open('b.txt') as f:
print f.read()
>>> a b c d e
#把列表写到字符串中去,并用空格隔开每个字符
list1 = [1,2,3,4,5,6]
with open('c.txt','w+') as f1:
# for i in list1:
# f1.write(str(i))
# f1.close()
f1.write(''.join([str(i)+' ' for i in list1 ]))
with open('c.txt') as f1:
print f1.read()
>>> 1 2 3 4 5 6
#把元组写到文件中去
tuple1 = ('1','2','a','b')
with codecs.open('d.txt','w+') as f2:
f2.write(str(tuple1) + '\n')
f2.close()
with codecs.open('d.txt') as f2:
print f2.read()
>>> ('1', '2', 'a', 'b')
#把字典写到文件中去
dict1 = {'a':'1','b':2,'c':3}
with open('e.txt','w+') as f3:
f3.write(str(dict1))
with open('e.txt') as f3:
print f3.read()
>>> {'a': '1', 'c': 3, 'b': 2}
最新文章
- HTML5笔记1——HTML5的发展史及标签的改变
- jQuery- 表单验证插件-Validation
- SQL Server中使用Check约束提升性能
- JavaWeb结合七牛云存储搭建个人相册服务
- ARMGNU伪指令
- Asp.Net Mvc Areas 的用法与好处
- 不用git将项目push到码云上
- fopen中r+和w+的区别
- 最近遇到的jsfl开发问题总结
- Swift关于Any,AnyObject,AnyClass的区别与联系
- 一排下去再上来的div
- JAVA IO 详解2
- MySQL查看数据库、表的占用空间大小
- perl 实现微信简版<;2>;
- 动态链接库 DLL
- kindeditor编辑器,图片上传功能齐全
- 编写程序,从vector<;char>;初始化string
- calling c++ from golang with swig--windows dll (三)
- Nginx整合tomcat,实现反向代理和负载均衡
- Go并发编程之美-CAS操作
热门文章
- libsm6 &; libgtk lost (QQ + WPS: Ubuntu)
- (10)centos搭建web服务器 (Nginx+ django)
- [Python Debug] SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
- OpenSSL使用3(基本原理及生成过程)(转)
- jQuery.parseHTML() 函数
- ubuntu归档管理器消失了?
- python数据分析入门学习笔记儿
- tts和字符集的关系--要求源和目的端的数据库字符集必须一样,国家字符集必须一样。
- IT行业是吃青春饭的吗?
- cocos2d-x 3.0游戏实例学习笔记 《跑酷》移植到android手机