zoukankan      html  css  js  c++  java
  • Python语言程序设计基础(7)—— 文件和数据格式化

    返回字符串

    file = input()
    
    #返回字符串
    fo = open(file,"r").read(6)
    print(fo)

    返回列表形式

    file = input()
    fo = open(file,"r")
    #print(fo)
    #返回列表形式
    print(fo.readlines(-1))
    file = input()
    fo = open(file,"r")
    
    for line in fo.readlines():
        print(line.replace('
    ',""))
    fo.close()
    file = input()
    fo = open(file,"r")
    for line in fo:
        print(line.replace('
    ',""))
    fo.close()

    w+ 

    打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。

    fname = input()
    fo = open(fname,"w+")
    ls = ["TreeDream","love","sea"]
    
    fo.writelines(",".join(ls))
    fo.seek(0)
    for line in fo:
        print(line)
    fo.close()

    csv

    国际通用数据存储格式,使用逗号分隔的表示方式

    fo = open("data.csv","r")
    '''
    ls = []
    for line in fo:
        line = line.replace('
    ',"")
        ls.append(line.split(","))
    print(ls)
    fo.close()'''
    
    for line in fo:
        line = line.replace('
    ', '')
        ls = line.split(',')
        lns = ""
        for s in ls:
            lns += "{}	".format(s)
        print(lns)
    fo.close()

    csv读写

    fr = open("data.csv","r")
    fw = open("out.csv","w")
    
    ls = []
    for line in fr:
        line = line.replace("
    ","")
        ls.append(line.split(','))
    print(ls)
    
    for i in range(len(ls)):
        for j in range(len(ls[i])):
            if ls[i][j].replace('.','').isnumeric():
                ls[i][j] = "{:.2%}".format(float(ls[i][j])/100)
                #print(ls[i][j])
    
    for row in ls:
        print(",".join(row))
        fw.write(",".join(row)+"
    ")

  • 相关阅读:
    大型网站架构系列——分布式消息队列
    docker 搭建lnmp环境以及docker常用命令
    编译PHP扩展amqp & php消息队列 rabbitmq
    python @staticmethod和@classmethod的作用
    Sqlalchemy model 文件自动生成
    正则表达式–零宽断言-赵兴壮
    php 编码规范
    MySQL8.0 InnoDB并行执行
    MySQL8.0 新特性 Hash Join
    MySQL8.0 redo日志系统优化
  • 原文地址:https://www.cnblogs.com/TreeDream/p/9825576.html
Copyright © 2011-2022 走看看