zoukankan      html  css  js  c++  java
  • python入门-文件

    1 读取文件

    with open('1.txt') as file_ojbect:
        contents = file_ojbect.read()
        print(contents.rstrip())

     with 自动体会文件的关闭  

    open 打开文件,然后返回一个文件对象

    把结果放到变量中,然后打印去掉右边空行的变量

    其他几个 读取文件的用法

    with open('1.txt') as file_ojbect:
        for line in file_ojbect:
            print(line.rstrip())
    
    
    
    filename = '1.txt'
    with open(filename) as file_ojbect:
        lines = file_ojbect.readlines()
    
    for line in lines:
        print(line.rstrip())
    
    
    filename = '1.txt'
    with open(filename) as file_ojbect:
        lines = file_ojbect.readlines()
    
    pi_string=''
    for line in lines:
        pi_string +=line.strip()
    
    print(pi_string)
    print(len(pi_string))

    2 写入文件

    filename = '3.txt'
    with open(filename,'w') as file_ojbect:
        file_ojbect.write("I love programming.
    ")
        file_ojbect.write("I love creating new games.
    ")

    打开 文件 然后写入如下内容

    3 追加文件

    filename = '3.txt'
    with open(filename,'a') as file_ojbect:
        file_ojbect.write("I love studying.
    ")
        file_ojbect.write("I love playing games.
    ")

    打开文件 然后追加如下内容

  • 相关阅读:
    领域建模
    中科院
    开放搜索服务OpenSearch
    GUIForDebug
    java: org.luaj.vm2.LuaError:XXX module not found lua脚本初始化出错(转)
    new TimerTask(robot)(转)
    lua-TestMore(转)
    Lua 数据库访问(转)
    推荐谈论高并发柱
    查看文章strncpy()功能更好的文章
  • 原文地址:https://www.cnblogs.com/baker95935/p/9437609.html
Copyright © 2011-2022 走看看