文件操作

 
'''
文件操作
'''
#文件只读模式 r只读 
# f = open('hello2.txt', 'r', encoding="UTF-8")
# data1 = f.read(10)
# print(data1)
# #移动指针到某个位置
# f.seek(0)
# #打印指针位置
# print(f.tell())
# data = f.read()
# f.readline()     #打印一行
# f.readlines()     #返回每一行组成的列表

#rb二进制只读
# f = open("hello.txt", "rb")
# data = f.read()

#文件只写模式 w只写 wb二进制只写
# f = open("hello2.txt", 'w', encoding="UTF-8")
# f.write("\n好诗好诗。\n")      #写入内容,会清空之前的文件

# wb 二进制只写
# f = open("hello2.txt", "wb")
# f.write("asd".encode())      #字符串转换编码格式

#文件追加模式
# f = open("hello2.txt", 'a', encoding="UTF-8")
# f.write("\n好诗好诗。")

#文件读写模式
# f = open('hello2.txt', 'r+', encoding="UTF-8")
# f.write("\n好诗好诗。")
# data = f.read()
# print(f.tell())
# f.write("\n好诗好诗。")

#文件写读模式   用的少
# f = open("hello2.txt", 'w+', encoding="UTF-8")

#文件追加读写模式
# f = open("hello2.txt", 'a+', encoding="UTF-8")

#文件清空
# f = open("hello.txt", 'a', encoding="UTF-8")
# f.seek(2) #seek无用
# f.truncate(10)

# print(data)

#读取多行 对于大数据效率低
# count = 0
# f = open("hello2.txt", 'r', encoding="UTF-8")
# for line in f.readlines():
    # count += 1
    # print('%2d %s' % (count, line))

#高效文件迭代器
# count = 0 
# f = open("hello.txt", "r", encoding="UTF-8")
# for line in f:
    # count += 1
    # #从第十行开始打印
    # if count > 9:
        # print("%2d %s" % (count, line))
  
#关闭文件句柄
# f.close()

#自动关闭文件句柄语法
with open("hello.txt", "r", encoding="UTF-8") as f, open("hello.txt.bak", "w", encoding="UTF-8") as f_new:
    for line in f:
        if "白日依山尽," in line:
            line = line.replace("白日依山尽,", "替换白日行,")
        f_new.write(line)

  

posted @ 2018-03-19 08:41  与君同悦  阅读(114)  评论(0)    收藏  举报