• 技术文章 >Python技术 >Python基础教程

    python两种不同的文件流读写

    小妮浅浅小妮浅浅2021-08-05 09:38:08原创2777

    1、使用try进行异常发现,使用while检测文件末尾进行读取

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    file_to_read = raw_input("Enter file name of tests (empty string to end program):")

    try:

        infile = open(file_to_read, 'r')

        while file_to_read != " ":

            file_to_write = raw_input("Enter output file name (.csv will be appended to it):")

            file_to_write = file_to_write + ".csv"

            outfile = open(file_to_write, "w")

            readings = (infile.readline())

            print readings

            while readings != 0:

                global count

                readings = int(readings)

                minimum = (infile.readline())

                maximum = (infile.readline())

    2、使用for遍历读取的每一行,进行一次性的读取和输入

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    result = list()

       with open('../test/parameter.txt') as  f:

           for line in f.readlines():

               temp = list()

               # 逐个遍历对应每一行元素,将之转为对应的数据

               b = line.strip(",][").split(',')

               if(len(b) >= 5):

                   b.pop()

               for a in b:

                   a = a.replace('[','').replace(']','')

                   temp.append(float(a))

               result.append(temp)

               #print("中途打印的temp是",temp)

               #print("加入到result中的结果是",result)

    以上就是python两种不同的文件流读写,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python文件流
    上一篇:python计算在月球的体重 下一篇:python删除str中特定字符的方法

    相关文章推荐

    • 如何将notepad绑定Python文件• 如何在终端打开Python文件• Python文件如何转换为字符串• python怎么import另一个python文件?• 在linux下怎么打开python文件• mac怎么执行python文件?• 如何把python文件做成exe文件• python文件如何形成安装包?• 怎么用vs编python文件• python文件打包为exe提示找不到路径是什么原因?• python文件为什么加utf-8• python文件新建之后怎么执行• 如何设置python文件默认使用spyder打开• pycharm怎么运行python文件• 如何直接运行某个python文件• python文件运行后被自动退出怎么办?• python文件打开闪退要怎么处理?• Python文件路径是什么?怎么写?• python文件路径的操作• python文件路径的组成• python文件导入相对路径• python文件的读取和写入

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网