python(8)-txt文件file操作-实例代码

       读写txt是编程应用中的常用基本操作。本文记录了python 操作txt文件的file 用法。本文包含创建,读单行、读多行,写入,追加操作的实现代码。file mode的用法和含义与C++,JAVA基本相同,r ,w,a ,a+都一样。只是python是弱字符类型,没有指针的概念,直接对变量操作。
      读取多行readlines 返回的是list.   附上python源码


1.创建

    1.创建一个文件叫mytest.txt ,里面输入如下信息:
        123456
        password=123456,length=6
        f=open('mytest.txt','w') 可以
        f=open('mytest.txt','a') 可以

    password='123456'
    length=len(password)
    #f=open('mytest.txt','a') 创建用a 和w都可以
    f=open('mytest.txt','w')
    f.write(password+'\n')
    f.write('password={},length={}\n'.format(password,length))
    f.close()

2.读取
    
1.读取文件所有内容 read() 返回的是str

    f=open('mytest.txt','r')
    content=f.read()
    print("content={},content的类型为={}".format(content,type(content)))
    f.close()

    """
    print 的输出如下:
    content=123456
    password=123456,length=6
    ,content的类型为=<class 'str'>

    """


    2.读取单行内容 readline()

    f = open('mytest.txt', 'r')
    content = f.readline()
    print("f.readline()="+content)
    f.close()
    """
    print 输出如下:
    f.readline()=123456
    """


    3.读取多行 readlines() 返回的是 list

    f = open('mytest.txt', 'r')
    for line in f.readlines():
         print('f.readlines()line= {}'.format(line))
    f.close()
    """
        print 输出如下:
        f.readlines()line= 123456
        f.readlines()line= password=123456,length=6

    """

 

 

posted @ 2019-12-15 16:52  jasmineTang  阅读(501)  评论(0)    收藏  举报