python中的文件操作

来源:互联网 发布:正装皮鞋推荐 知乎 编辑:程序博客网 时间:2024/05/29 18:33

python中与文件有关的知识如下

1 文件的基本处理(三个步骤):打开文件----->文件操作------>关闭文件

   打开文件:open()

  eg.   打开一个名为“numbers . dat”的文本文件 
           infile = open (“numbers.dat”, “r”)

   文件操作(读取和写入)

           读取:read() 返回值为包含整个文件内容的一个字符串 
       readline() 返回值为文件下一行内容的字符串。 
       readlines() 返回值为整个文件内容的列表,每项是以换行符为结尾的一行字符串。
            写入:write():把含有本文数据或二进制数据块的字符串写入文件中。 
      writelines():针对列表操作,接受一个字符串列表作为参数,将它们写入文件。   
    关闭文件 
close()

2 文件操作的例子

   (1) 文件的遍历是文件操作中最为常见的操作,针对文件的操作,有如下的文件遍历的模板框架:

   文件遍历框架: file = open (someFile, "r") 

                           for line in file:  

#处理一行文件内容 

     file.close() 

     (2)文件拷贝

 

#文件拷贝# def main():#     f1 = raw_input("enter a source file:").strip()    #strip()默认删除空白符(包括'\n', '\r',  '\t',  ' ')#     f2 = raw_input("enter a source file:").strip()##     infile = open(f1,"r")#     outfile = open(f2,"w")##     countLines = countChars = 0#     for line in infile:#         countLines += 1#         countChars += len(line)#         outfile.write(line)#     print countLines,"lines and",countChars,"chars copied"##     infile.close()#     outfile.close()## main()
 (3)根据数据文件定义行走路径

   

  

   

   实现方法:

   1)引入turtle库

2)设置窗口信息和Turtle画笔

3)读取数据文件到列表中

4)根据每一条数据记录进行绘制

5)画笔回到原点

    实现代码:

   

import turtledef main():    #设置窗口信息    turtle.title("数据驱动的动态路径绘制")    turtle.setup(800,600,0,0)    #设置画笔    pen = turtle.Turtle()    pen.color("red")    pen.width(5)    pen.shape("turtle")    pen.speed(5)    #读取文件    result = []    file = open('C:/Users/Administrator/Desktop/data.txt','r')    for line in file:        result.append(list(map(float,line.split(","))))   #关键点(把读取的文件内容的每一行内容通过‘,’进行切片,
                                                          #返回字符串列表,再通过map()来将返回的字符串列表转换为浮点类型
                                                          #最后再转换为列表,追加到result列表中)    print(result)    #动态绘制    for i  in range(len(result)):        pen.color(result[i][3],result[i][4],result[i][5])        pen.forward(result[i][0])        if result[i][1]:            pen.rt(result[i][2])        else:            pen.lt(result[i][2])    pen.goto(0,0)    turtle.done()if __name__ == '__main__':    main()

   

  

原创粉丝点击