python筆記:文件操做

一、逐行打印整個文件 spa

# -*- coding: utf-8 -*-
f = open("test",'r',encoding="utf-8") count = 0 for line in f: print(line.strip()) #strip忽略空格或換行符 count += 1

注意:code

1)默認模式爲r(讀),w(覆蓋),a(追加),r+(讀寫),w+(寫讀),a+(追加讀寫),rb(二進制文件);blog

2)strip()方法用於移除字符串頭尾指定的字符(默認爲空格或換行符)或字符序列。該方法只能刪除開頭或是結尾的字符,不能刪除中間部分的字符;ip

 

使用with語句utf-8

會自動關閉文件。字符串

# -*- coding: utf-8 -*-

with open("test","r",encoding="utf-8") as f:
    for line in f:
        print(line.strip())

 

二、打印和移動光標it

#打印光標
print(f.tell())

#移動光標
f.seek(10)

 

三、修改文件內容class

# -*- coding: utf-8 -*-

f = open("test","r",encoding="utf-8")
f_new = open("test.tmp","w",encoding="utf-8")

for line in f:
    if "你好呀" in line:
        line = line.replace("你好呀","您好啊")
    f_new.write(line)
f.close()
f_new.close()

新的文件test.tmp即爲修改後的文件test

相關文章
相關標籤/搜索