请将文件data1.csv的每行的空格去掉并按照列逆序排列,数据之间用分号隔开,将结果存放在data3.csv文件并输出。


import csvdef readfile(filename):with open(filename,"r",encoding="utf-8-sig") as f:text=f.read()return textdef filereverse(filename1,filename2):with open(filename1,"r",encoding="utf-8-sig") as f:lst=f.readlines()with open(filename2,"w",encoding="utf-8-sig") as f:for line in lst:line = line.replace("\n","")ls=line.split(",")ls=ls[::-1]line=";".join(ls)line=line+"\n"f.write(line)filepath1="txt\\data1.csv"
filepath2="txt\\data3.csv"text=readfile(filepath1)
print("{}文件:\n{}".format(filepath1,text))filereverse(filepath1,filepath2)
text=readfile(filepath2)
print("{}文件:\n{}".format(filepath2,text))

用两种方法求文件“latex.log”的文件总行数、除了空行以外的文件行数、除了空行以外的不重复的文件行数。

def filelines1(filename):with open(filename,'r',encoding='utf-8') as f:cnt1=0cnt2=0lst=[]for line in f:cnt1=cnt1+1if line!='\n':cnt2=cnt2+1if line not in lst:lst.append(line)cnt3=len(lst)return (cnt1,cnt2,cnt3)def filelines2(filename):                                    with open(filename,'r',encoding='utf-8') as f:lst=f.readlines()cnt1=len(lst)lst.remove("\n")cnt2=len(lst)cnt3=len(list(set(filename)))return (cnt1,cnt2,cnt3)filepath="TXT\\latex.log"print("方法一:文件一行一行访问")
cnt1,cnt2,cnt3=filelines1(filepath)
print("{} 文件总行数:{}".format(filepath,cnt1))
print("{} 除了空行以外的文件行数:{}".format(filepath,cnt2))
print("{} 除了空行以外不重复的文件行数:{}\n".format(filepath,cnt3))print("方法二:文件读出到列表中")
print("{} 文件总行数:{}".format(filepath,cnt1))
print("{} 除了空行以外的文件行数:{}".format(filepath,cnt2))
print("{} 除了空行以外不重复的文件行数:{}\n".format(filepath,cnt3))

调查问卷随机产生,写入文件。统计各评语出现的次数,生成字典。把统计结果再写入文件。


import randomdef Qnaire(lst,n):  # 从lst中,随机产生n份调查问卷,存于字符串并返回result=[]for i in range(n):x=random.choice(comments)result.append(x)text=','.join(str(i) for i in result)return textdef Qnairewrite(filename,text):  # 将字符串text写入文件filename中with open(filename,'w',encoding='utf-8') as f:f.write(text)  def Qnaireread(filename):   # 将文件内容读出,放于字符串中,并返回with open(filename,'r',encoding='utf-8') as f:txt=f.read()   return txtdef cntComments(text):  # 对字符串text,统计各评语出现的次数,生成字典,并返回s=text.split(',')dic={}for i in s:dic[i]=dic.get(i,1)+1 return dicdef dictappend(filename,dicCnts):  # 往将调查问卷的结果dicCnts,追加到文件中filenamewith open(filename,'a+',encoding='utf-8') as f:f.write("\n根据统计,对伙食感觉:")for k,v in dicCnts.items():f.write("\n{}的学生:{}人".format(k,v))f.write("\n调查结果中,出现次数最多的评语是:")  f.write(max(dicCnts))  pathfile="TXT\\result1.txt"comments=['不满意','一般','满意','很满意']
result=Qnaire(comments,90)   # 产生90份随机调查问卷结果,放于result中
Qnairewrite(pathfile,result)     # 将调查问卷结果result,写入文件pathfileresult=Qnaireread(pathfile)   # 将文件pathfile中内容读出,放于result中
print("\n{} 调查问卷(随机产生):\n\n{}".format(pathfile,result))dicCnts=cntComments(result)  # 将调查结果result,统计各评语出现的次数,生成字典,放于dicCnts中
print("\n调查问卷中各评语的统计结果:\n{}".format(dicCnts))dictappend(pathfile,dicCnts) # 将各评语出现的次数dicCnts,追加写入文件pathfile中result=Qnaireread(pathfile)   # 将文件pathfile中内容读出,放于result中
print("\n{} 调查问卷及各评语的统计结果:\n\n{}".format(pathfile,result))

创建“通信录.csv”文件。


         "小亮":{"手机":"13913000002","QQ":"13913000002","微信":"13913000002"},"小刚":{"手机":"13913000003","QQ":"18191220003","微信":"gang1004"},"大刘":{"手机":"13914000001","QQ":"18191230001","微信":"liu666"},"大王":{"手机":"13914000002","QQ":"18191230002","微信":"jack_w"},"大张":{"手机":"13914000003","QQ":"18191230003","微信":"13914000003"}}
a=[]
for k,v in dictTXL.items():a.append(k)for c,d in v.items():a.append(d)
b=[]
for i in range(len(a)+4):if i==0:b.append(["姓名","手机","QQ","微信"])if i!=0 and i%4==0:b.append(a[i-4:i])
print(b)import csv
with open('通信录.csv','a',newline='',encoding='utf-8-sig')as 通信录csv:writer=csv.writer(通信录csv)writer.writerows(b)n=input('姓名:')
for k,v in dictTXL.items():if k==n:for e,f in v.items():print(e,f)

随机组谜语卷


import os
import csv
import random#定义函数打开文件,将谜语集读成字典
def getDic(fileName):dic={}with open(fileName,"r",encoding="utf-8") as file:reader=csv.reader(file)next(reader)            #跳过文件中的表头for row in reader:dic[row[0]]=row[1]  #谜面为作为key,谜底作为valuereturn dic
#定义函数根据dic生成长度为n的试卷列表,每一个元素为一套试卷列表
def creatPapers(dic,n):tests=[]items=list(dic.keys())for i in range(n):random.shuffle(items)ls=items[:10]tests.append(ls)return tests#定义函数lsPapers和lsAnswers生成n个试卷文件和n个答卷文件
def createFiles(lsPapers,lsAnswers,n):for i in range(n):fpn="paper" + str(i+1) + ".txt"with open(fpn,"w",encoding="utf-8") as filep:filep.writelines([item + "\n" for item in lsPapers[i]])fan="answer" + str(i+1) + ".txt"with open(fan,"w",encoding="utf-8")as filea:filea.writelines([item + "\n" for item in lsAnswers[i]])#主程序,生成n套试卷和答卷
os.chdir("C:\\202042801117 林琦雯\\txt")
fn="儿童谜语集.csv"
n=5
riddles=getDic(fn)
papers=creatPapers(riddles,n)answers=[]                          #根据谜面列表papers生成对应的答案列表
for paper in papers:ans=[riddles[item] for item in paper]answers.append(ans)
createFiles(papers,answers,n)

统计《哈姆雷特》中出现频率最高的前10个单词。


def getText(text):text = text.lower()for ch in ",.;?-:\'":text = text.replace(ch," ")return text#编码函数统计单词出现频率
#text 为待统计的文本,topn表示取频率最高的单词个数
def wordFreqs(text,topn):words = text.split( )            # 将文本分词counts = { }for word in words:counts[word] = counts.get(word,0) + 1excludes={"the","and","to","of","a","be","it","is","not","but"}for word in excludes:del(counts[word])items = list(counts.items())items.sort(key=lambda x:x[1], reverse=True)return items[:topn]#编写主程序,调用函数
try:with open (r"C:\202042801117 林琦雯\txt\hamlet.txt",'r',encoding='utf-8') as file:text = file.read()text = getText(text)freqs = wordFreqs(text,10)
except IOError:print("文件不存在,请确认!\n")
else:try:with    open(r"C:\202042801117 林琦雯\txt\hamlet_词频.txt",'w',encoding='utf-8')as fileFreq:items=[ word + "\t" + str(freq) + "\n" for word, freq in freqs]fileFreq.writelines(items)except IOError:print("写入文件出错")for word,freq in freqs:print("{:<10}{:>}".format(word,freq))

文件处理篇python相关推荐

  1. Python文件及目录操作(基本文件操作篇)

    ​ 活动地址:CSDN21天学习挑战赛 学习的最大理由是想摆脱平庸,早一天就多一份人生的精彩:迟一天就多一天平庸的困扰. 学习日记 目录 学习日记 一.前言 二.基本文件操作 1.创建和打开文件 2. ...

  2. C语言第五篇 python调用C语言写的动态链接库DLL文件

    学习目标:1.学会C语言写windows下的DLL文件.2.用gcc命令将C程序编译成DLL文件.3.学会用python调用C语言写的DLL. 学习内容1:先用C语言写一个简单程序,先建立dll.c文 ...

  3. python导入txt文件并绘图-Python读取txt某几列绘图的方法

    晚上帮同学用Python脚本绘图,大概需求是读取一个txt文件的两列分别作为x和y的值,绘图即可,代码如下: #coding:utf-8 import numpy as np import matpl ...

  4. python文件读取输出-python分批定量读取文件内容,输出到不同文件中的方法

    一.文件内容的分发 应用场景:分批读取共有358086行内容的txt文件,每取1000条输出到一个文件当中 # coding=utf-8 # 分批读取共有358086行内容的txt文件,每取1000条 ...

  5. python如何移动文件却不覆盖现有文件_解决python不能覆盖文件内容的方法

    解决python不能覆盖文件内容的方法 发布时间:2020-07-15 11:42:17 来源:亿速云 阅读:62 作者:清晨 这篇文章将为大家详细讲解有关解决python不能覆盖文件内容的方法,小编 ...

  6. [转帖]虚拟内存探究 -- 第二篇:Python 字节

    虚拟内存探究 -- 第二篇:Python 字节 http://blog.coderhuo.tech/2017/10/15/Virtual_Memory_python_bytes/是真看不懂哦  翻译 ...

  7. OpenCV快速入门篇(Python实现)

    OpenCV快速入门篇(Python实现) 转载自:https://blog.csdn.net/feilong_csdn/article/details/82750029 本系列python版本:py ...

  8. python怎么调用另一个py文件的变量,Python中py文件引用另一个py文件变量的方法

    Python中py文件引用另一个py文件变量的方法 最近自己初学Python,在编程是遇到一个问题就是,怎样在一个py文件中使用另一个py文件中变量,问题如下: demo1代码 import requ ...

  9. python移动文件的函数_移动并重命名2000个文件,用Python,只需3秒

    原标题:移动并重命名2000个文件,用Python,只需3秒 作者:陈熹.刘早起 来源:早起Python 今天介绍的案例是如何利用Python来 自动化移动.修改.重命名文件/夹,这样的操作在日常办公 ...

最新文章

  1. php zblog 侧边栏样式_zblogphp版如何实现导航栏下拉框
  2. 视频监控智能算法的关键问题分析
  3. Docker是个啥?
  4. 为什么要重映射那个GPIO_Remap_SWJ_JTAGDisable
  5. 大公司里怎样开发和部署前端代码
  6. 文件上传之Apache commons fileupload使用
  7. VC调用QT的UIDLL
  8. C/C++ 文件读取操作 竞赛篇
  9. Kotlin的匿名方法实现接口回调
  10. RN listView使用
  11. 易班 华南理工大学 新生入学教育在线考试 题库共503题
  12. 【游戏开发3D数学笔记】1.有话说在前面
  13. 现浇板弹性计算还是塑性计算_板塑性与弹性.doc
  14. matlab画EBSD的极图,EBSD技术原理及系统.PDF
  15. 微信js-sdk+JAVA实现分享接口
  16. Microsoft Office LTSC ProPlus 2021 Volume(含:Project + Visio)离线命令方式安装说明(原创)
  17. SPSS异方差检验的实现
  18. sql未保存文档找回
  19. 史上最全Android版本号信息:)
  20. ESP8266开发板刷WI-PWN固件(wifi杀手)教程(详细)

热门文章

  1. 【sketchup 2021】草图大师的高级工具使用1【不透明度高级使用、填充材质高级使用】
  2. Skimage包的安装及使用时报错ImportError: cannot import name ‘compare_psnr’ from ‘skimage.measure’
  3. 三个月5位老员工离职!苹果健康团队被曝内部分歧严重,员工扎堆儿离开
  4. CSS 的快乐:画一个可爱的三只小鸟 Button
  5. 听了一天的队歌,Liverpool F.C.的最棒
  6. 【设计模式系列19】状态模式原理分析及其和策略模式,责任链模式的区别
  7. Box2D 物理引擎入门
  8. 在office word 里无法用搜狗输入中文
  9. 如何在Win10 Win11家庭版中启用组策略
  10. 优化关键词,实现排名优势!