python—常见文件读写

class MyFile:
    def __init__(self,filename="d:\\"):
        self.filename=filename
    def ReadTxt(self):
      with open(self.filename, 'r') as f:
        for s in f.readlines():
            print(s, end='')
#-----------------------写入txt文件-------
    def WriteTxt(self,dataset):
      with open(self.filename, 'w') as f:
#          f.writelines(dataset) 不能换行写
          for yy in dataset:
              f.write(str(yy)+"\t") #写入字符串\
      print("写入成功!")
#-----------------------二进制文件--------------
    def Readbinary(self):
      with open(self, 'rb') as f:
          b = f.read()
          print(b)
#-------------------------------------------------
    def Writebinary(self):    
      with open(self.filename, 'wb') as f:
          f.write(b'123')   #写入字节数据
          f.write(b'abc')   #写入字节数据
#-------------------文件定位seek使用方法------------------------------
    def ReadBlock(self,BlockSize=1024):
      import os
      with open(self.filename,'r')  as f:  #创建或打开文件data.
          while True:
              Block=f.read(BlockSize)
              if not Block:
                  break
              print(Block)
    def ReadLine(self,BlockSize=1024):
      import os
      with open(self.filename,'r')  as f:  #创建或打开文件data.
          while True:
              Line=f.readline()
              if not Line:
                  break
              print(Line)
#---------------------.gz文件读写方式(将现有文件data1.txt内容写入后压缩)---------------------------------
    def  gzipfile(self):
        import sys, gzip
        filenamezip = self.filename + '.gz'   #file extension .gz
        # gzip compression 
        with gzip.open(filenamezip, 'wt') as f:  
            for s in open(self.filename, 'r'):
                f.write(s)
                # gzip decompression
        for s in gzip.open(filenamezip, 'r'):
            print(s)
#---------------------读入csv文件(不带标题)---------
    def Readcsv(self):
        import csv
        with open(self.filename, newline='') as f:  #打开文件
            f_csv = csv.reader(f)    #创建csv.reader对象
            headers = next(f_csv)    #标题
            print(headers)           #打印标题(列表)
            for row in f_csv:        #循环打印各行(列表)
                print(row)
#-------------------------写入csv文件------------------------------------------------
    def Writecsv(self):
        import csv
        rows = [('学号', '姓名', '性别', '班级', '语文', '数学', '英语'),
                ('101511', '宋颐园', '男', '一班', '72', '85', '82'),
                ('101513', '王二丫', '女', '一班', '75', '82', '51')]
        with open(self.filename,'w', newline='') as f:  #打开文件
            f_csv = csv.writer(f)       #创建csv.writer对象
            f_csv.writerows(rows)     #写入多行(数据)
            print("写入成功!")
#-------------------读入所有txt文件-----------------------------------
    def ReadAllTypeFile(self,PathDirectory):
        import fileinput, glob
        txtfiles = glob.glob(PathDirectory)
        with fileinput.input(files=txtfiles) as f:
            for line in f:
                print(f.filename(), f.lineno(), line, end='')
MyWrite=MyFile()
MyWrite.filename="d:\\1.csv"
MyWrite.Writecsv()
MyWrite.filename="d:\\1.txt"
MyWrite.WriteTxt(["123","my name is Jack!","End"])


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值