Python文件操作
来源:互联网 发布:淘宝客怎么看 编辑:程序博客网 时间:2024/06/16 06:25
文件打开:
Infile=open(“num.dat”,”r”)#r,w为读和写文本文件
Infile=open(“music.mp3”,”rb”)#rb,wb为读和写二进制文件
文件读取:
read():返回包含整个文件内容的字符串
readline():返回值为文件下一行内容的字符串
readlines():返回值为文件内容列表,每项以换行符结尾
写入文件:
write():把字符串写入文件
writelines():针对列表操作,接受一个字符串列表作为一个参数写入
文件遍历:
for line in file: #每行处理
文件拷贝:
fname1=raw_input().strip()#去空格 fname2=raw_input().strip() f1=open(fname1,"r") f2=open(fname2,"w") for line in f1: f2.write(line) f1.close() f2.close()
文件合并实例:
TelInformation.txt
姓名: 电话:嘻嘻 1333333
男男 82782
EmailInformation.txt
姓名: 邮箱:
嘻嘻 123@163.com
东东 124@qq.com
Information.txt
嘻嘻 1333333 123@163.com男男 82782 not have email
东东 not have tel 124@qq.com
# -*- coding: utf-8 -*-from math import *from turtle import *def main(): f1=open("TelInformation.txt","r") f2=open("EmailInformation.txt","r") f3=open("Information.txt","w") f1.readline();#第一行信息没用 f2.readline() lines1=f1.readlines() lines2=f2.readlines() list1_name=[] list1_tel=[] list2_name=[] list2_email=[] #将文件1的姓名和tel,文件2的姓名和email单独存储 for line in lines1: list1_name.append(line.split()[0]) list1_tel.append(line.split()[1]) for line in lines2: list2_name.append(line.split()[0]) list2_email.append(line.split()[1]) list3=[]#合并信息放入 #索引方式遍历列表1的姓名 for i in range(len(list1_name)): if list1_name[i] in list2_name: pos=list2_name.index(list1_name[i]) list3.append(list1_name[i]+' '+list1_tel[i]+' '+list2_email[pos]+'\n') else: list3.append(list1_name[i] + ' ' + list1_tel[i] + ' ' + 'not have email'+'\n') #处理文件1中没有的姓名 for i in range(len(list2_name)): if list2_name[i] not in list1_name: list3.append(list2_name[i] + ' ' + "not have tel" + ' ' +list2_email[i]+'\n') f3.writelines(list3) f1.close() f2.close() f3.close()main()
阅读全文
0 0
- Python 文件操作常用操作
- [python]python操作xml文件
- Python文件操作
- python文件目录操作
- Python文件操作
- Python文件操作
- python 文件操作
- python 文件操作
- Python 文件操作
- python 文件操作
- Python文件操作
- python 文件读写操作
- Python文件读写操作
- python文件目录操作
- Python的文件操作
- python常见文件操作
- python - 文件操作
- python文件操作
- K-means聚类算法
- 给多说评论系统增加颜文字
- 版本更新
- Linux下MySQL 5.5、5.6和5.7的RPM、二进制和源码安装(下)
- baseadapter的二次封装
- Python文件操作
- hibernate个人总结1
- poj 2318 TOYS
- Ubuntu命令点滴积累
- Android蓝牙开发
- 设计模式学习(C++实现)3——单例模式
- springMVC 中接收前端传递的对象、数组等数据的方式详解
- 透明控件点击事件穿透的解决办法
- git的commit/push/add