zoukankan      html  css  js  c++  java
  • 文件操作

    1.with打开

    with open(r'E:py	ext_filespi.txt') as file_object:  # 在冒号前加r表示以原始字符串方式指定路径,否则会出现	的转义符报错或者用\表示路径
        contents = file_object.read()
        print(contents.strip())

    2.逐行读取及打印

    filename = 'E:py\text_filespi.txt'
    with open(filename) as file_object:  # 在冒号前加r表示以原始字符串方式指定路径,否则会出现	的转义符报错或者用\表示路径
        contents = file_object.readlines()  # 逐行读取
        for i in contents:
            print(i.strip())  # 逐行打印,去除空行的空格

    3.调整指针

    filename = r'E:py	ext_filespi.txt'
    with open(filename) as file_object:  # 在冒号前加r表示以原始字符串方式指定路径,否则会出现	的转义符报错或者用\表示路径
        contents = file_object.readlines()  # 逐行读取
        # file_object.seek(20)#调整指针位置
        print(file_object.tell())  # 42获取指针位置
    a = ''
    for i in contents:
        a = a + i.strip()  # 拼接字符串
    print(a)  # 3.141592653589793238462643383279
    print(len(a))  # 32

     4.替换字符

    with open(r'e:py	ext_filespi.txt', 'r', encoding='utf-8')  as abc:
        for i in abc.readlines():
            c = i.replace('Python', 'C++')
            print(c.strip())
    '''In C++ you can create class
    In C++ you can use loops
    In C++ you can look at function'''
  • 相关阅读:
    luogu P1382 楼房
    luogu P1908 逆序对
    5.28 模拟赛
    POJ 2991 Crane
    残(矩阵快速幂)
    AC日记——拍照 洛谷 P3410
    AC日记——[CQOI2014]危桥 洛谷 P3163
    AC日记——【模板】二分图匹配 洛谷 P3386
    AC日记——[ZJOI2009]假期的宿舍 cogs 1333
    AC日记——城市 洛谷 P1401
  • 原文地址:https://www.cnblogs.com/xusuns/p/8303840.html
Copyright © 2011-2022 走看看