zoukankan      html  css  js  c++  java
  • 文件写入有读取

    1.文件的读取
    首先我们要准备一段已经写好的文件。
    test.txt文件写入一段话:这是第一段测试文件。
    >>> f= open('test.txt','r')
    >>> f.read()
    '这是第一段测试文件'
    >>> f.close()

    2.文件的写入
    >>> f = open('test.txt','w')
    >>> f.write('this is a test ')
    15
    >>> f.close()
    >>> f= open('test.txt','r')
    >>> f.read(5)
    'this '
    >>> f.readline()
    'is a test '
    >>> f.read()

    3.分行读取
    f = open('test.txt', 'r')

    content = f.readlines()

    i=1
    for temp in content:
    print((i, ‘:’,temp))
    i+=1
    f.close()

    4.with语句
    with 语句会自动关闭文件,不会造成文件的意外丢失。
    实例:
    文件中已经写入的一个文件为test.txt
    >>> with open('test.txt') as f:
    content=f.read()
    print(content)


    this is a test
    this is a test
    this is a test
    this is a test
    this is a test

    5.在文件目录下读取文件
    python默认只会在安装python的目录下查找文件,如果要打开在python目录下的子目录文件则需要指定目录查找文件。
    >>> with open('python_filepython.txt') as f:
    content = f.read()
    print(content)


    这是一段测试文件。
    这是一段测试文件。
    这是一段测试文件。
    这是一段测试文件。
    这是一段测试文件。
    这里要说明的是在liunx/xos 中是斜杠符,在windos中是反斜杠符号

    6.逐行读取文件内容
    >>> f = 'python_filepython.txt'
    >>> with open(f) as e:
    for lines in e:
    print(lines.rstrip())


    这是一段测试文件。
    这是一段测试文件。
    这是一段测试文件。
    这是一段测试文件。
    这是一段测试文件。
    这其中由于遍历e文件中的每行文字,会在打印的时候产生过多的空格,在print 函数中加入 rstrip()函数可以消除打印机结果中的空格。

    7.创建一个包含文件内容的列表
    >>> f = 'python_filepython.txt'
    >>> with open(f) as e :
    lines = e.readlines()

    >>> for line in lines:
    print(line.rstrip())

    这是一段测试文件。
    这是一段测试文件。
    这是一段测试文件。

    8.创建一个包含文件的字符串
    >>> f = 'python_filepython.txt'
    >>> with open(f) as e :
    lines = e.readlines()

    >>> for line in lines:
    >>> str = ''
    >>> for line in lines:
    str +=line
    >>> str
    '这是一段测试文件。 这是一段测试文件。 这是一段测试文件。 这是一段测试文件。 这是一段测试文件。'
    >>> len(str)
    49

    注意:python在读取文件时默认将所有文件解读为字符串类型。如果我们要使用其中的整数,我们需要int()函数转化为整数,要用浮点数我们就使用float()函数转化为浮点数。

    9.写入一个文件
    >>> with open(f,'w') as e:
    e.write('我是一个兵来自老百姓 ')
    e.write('我爱python,但我更爱你 ')

    10.附加文件。
    用附加文件打开文件,不会覆盖原文件,写入的文件将被自动附加到文件末尾,假如文件不存在,则会创建一个空文件夹。

    11.关于尝试
    1.我们可以尝试编写一个程序,这个程序在提示用户输入用户名之后做出响应,将名字添加到guest文件当中。
    2.建立访客名单。写一个while循环,提示用户输入其名字后,在屏幕答应一句问候语,并将一条访问记录添加到文件guest-name.txt文件中,并确保这个文件每条记录都独占一行。
    3.关于编程的调查。编写一个while循环,访问用户为何喜欢编程,每当用户输入一条原因之后,都将其添加到一个包含所有原因的文件夹之中。
    ---------2018年4月9日

     

  • 相关阅读:
    redis 5.0.5集群部署
    python 继承、多继承与方法重写(二)
    python 脚本监控硬件磁盘状态并发送报警邮件
    k8s 应用程序获取真实来源ip
    yolov5 安装尝试
    安装pygrib
    ubuntu编译ecodes
    python mpi实验
    mint install gaussian 16
    flask 使用工程外的static文件位置
  • 原文地址:https://www.cnblogs.com/user0712/p/8763635.html
Copyright © 2011-2022 走看看