zoukankan      html  css  js  c++  java
  • python开发应用-本地数据获取方法

          文件的打开、读写和关闭

       文件的打开:

    file_obj=open(filename,mode='r',buffering=-1,...)

    filename是强制参数

    mode是可选参数,默认值是r

    buffering是可选参数,默认值为-1(0代表不缓冲,1或大于1的值表示缓冲一行或指定缓冲区大小)

       

    f1=open('e:/test/data.txt')                                
    f1=open('e:\testdata.txt')  
    f2=open(r'e:/test/data.txt','w')  
    

      文件相关函数

        返回值:

    1、open()函数返回一个文件(file)对象

    2、文件对象可迭代

    3、有关闭和读写文件的相关的函数/方法

    写文件:

    file_obj.write(str):讲一个字符串写入文件

       

    with open('e:\test\firstpro.txt','w') as f:  
    f.write('Hello,World!')  
    

      

    file_obj.read(size):从文件中至多读出size字节数据,返回一个字符串

    file_obj.read():读文件直到文件结束,返回一个字符串

       

    with open('e:/test/firstpro.txt') as f:  
        p1=f.read(5)  
        p2=f.read()  
      
          
     p1  
    'Hello'  
     p2  
    ',World!'  
    

      

    其它读写函数:

    file_obj.readlines():读取多行数据

    file_obj.readline():读取一行数据

    file_obj.writelines():写入多行数据

      

    with open('e:/test/data.txt') as f:  
    f.readlines() 
    

      

    文件读写例子:将文件data.txt中的字符串前面加上1、2、3、4、...后写入到另一个文件data1.txt中。

    data.txt

        

    apple  
    banana  
    car  
    pear
    

      

    with open('e:/test/data.txt') as f1:  
        cNames=f1.readlines()  
        for i in range(0,len(cNames)):  
            cNames[i]=str(i+1)+' '+cNames[i]  
    with open('e:/test/data1.txt','w') as f2:  
        f2.writelines(cNames)  
    

      

    其它文件相关函数:

    file_obj.seek(offset,whence=0):在文件中移动文件指针,从whence(0表示文件头部,1表示当前位置,2

    1. 表示文件尾部)偏移offset个字节,whence参数可选,默认值为0。
      with open('e:/test/data.txt','a+') as f:  
          f.writelines('
      ')  
          f.writelines(s)  
          f.seek(0)  
          cNames=f.readlines()  
          print(cNames)  
      

        

      ['apple
      ', 'banana
      ', 'car
      ', 'pear
      ', 'Tencent Technology Company Limited'] 
      

        

      标准文件:

      stdin:标准输入

      stdout:标准输出

      stderr:标准错误

      newName=input('Enter the name of new company:')  
      Enter the name of new company:Alibaba  
       print(newName)  
      Alibaba  
      

        实际上是sys模块提供的函数实现的

    2. import sys  
       sys.stdout.write('hello')  
      hello5  
      

        

  • 相关阅读:
    五、mariadb遇到的坑——Linux学习笔记
    四、CentOS 安装mariadb——Linux学习笔记
    [搬运] C# 这些年来受欢迎的特性
    [搬运] 写给 C# 开发人员的函数式编程
    [搬运]在C#使用.NET设计模式的新观点
    在容器中利用Nginx-proxy实现多域名的自动反向代理、免费SSL证书
    [翻译]在 .NET Core 中的并发编程
    [翻译] 使用ElasticSearch,Kibana,ASP.NET Core和Docker可视化数据
    .NET Core:使用ImageSharp跨平台处理图像
    .NET Core开源组件:后台任务利器之Hangfire
  • 原文地址:https://www.cnblogs.com/68xi/p/8564634.html
Copyright © 2011-2022 走看看