f = open('./test2.txt',mode='w',encoding='utf-8')
f.write('嫉妒是自己的敵人,也是他人的敵人')
f.flush()
f.close()
結果:
f = open('./test2.txt',mode='wb')
f.write('勇敢乃是自信與害怕中間之道。—— 亞里士多德'.encode('utf-8'))
f.flush()
f.close()
結果:
str = '''智慧勤勞和天才,高於顯貴和富有。—— 貝多芬
受任於敗軍之際,奉命於危難之間。—— 諸葛亮
要成功,需要跟成功者在一起。—— 陳安之
'''
f = open('./test2.txt',mode='w+',encoding='utf-8')
f.write(str) #寫完,光標移到文件末尾
f.seek(0) #光標移到文件頭,
start1 = f.tell() #當前光標位置(單位:字節)
s1 = f.read(2) #讀取長度
start2 = f.tell()
f.seek(9) #參數1:光標相對於文件頭第七個字節,參數2:0=文件頭,1=當前光標位置,2=文件末尾
s2 = f.read() #默認讀取光標後面所有
f.flush()
f.close()
print(s1)
print(s2)
print(start1,start2)
結果:
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
智慧
勞和天才,高於顯貴和富有。—— 貝多芬
受任於敗軍之際,奉命於危難之間。—— 諸葛亮
要成功,需要跟成功者在一起。—— 陳安之
0 6
文件:
f = open('./test2.txt',mode='a',encoding='utf-8')
f.write('\n健康不是一切,但沒有健康就沒有一切。—— 吳階平')
f.flush()
f.close()
結果:
f = open('./test2.txt',mode='ab')
f.write('\n畫工須畫雲中龍,爲人須爲人中雄。—— 秋瑾'.encode('utf-8'))
f.flush()
f.close()
結果:
f1 = open('./test.txt',mode='r',encoding='utf-8')
s1 = f1.readline()
f1.seek(0)
s2 = f1.readlines()
f1.seek(0)
s3 = f1.readable()
f1.close()
print(s1,s2)
print(s3)
結果:
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
鄧潤髮
['鄧潤髮\n', 'abcdefghhjjk\n', '鄧星星\n', '達叔\n', '林青霞\n', '關之琳']
True
文件:
f = open('./test2.txt',mode='rb')
s = f.read()
f.close()
print(s)
print(s.decode('utf-8'))
結果:
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
b'\xe5\xab\x89\xe5\xa6\x92\xe6\x98\xaf\xe8\x87\xaa\xe5\xb7\xb1\xe7\x9a\x84\xe6\x95\x8c\xe4\xba\xba\xef\xbc\x8c\xe4\xb9\x9f\xe6\x98\xaf\xe4\xbb\x96\xe4\xba\xba\xe7\x9a\x84\xe6\x95\x8c\xe4\xba\xba\r\n\xe5\x81\xa5\xe5\xba\xb7\xe4\xb8\x8d\xe6\x98\xaf\xe4\xb8\x80\xe5\x88\x87\xef\xbc\x8c\xe4\xbd\x86\xe6\xb2\xa1\xe6\x9c\x89\xe5\x81\xa5\xe5\xba\xb7\xe5\xb0\xb1\xe6\xb2\xa1\xe6\x9c\x89\xe4\xb8\x80\xe5\x88\x87\xe3\x80\x82\xe2\x80\x94\xe2\x80\x94 \xe5\x90\xb4\xe9\x98\xb6\xe5\xb9\xb3'
嫉妒是自己的敵人,也是他人的敵人
健康不是一切,但沒有健康就沒有一切。—— 吳階平
f1 = open('./test.txt',mode='r',encoding='utf-8')
count = 0
for line in f1:
count+=1
print(line)
print(count)
結果:
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
鄧潤髮
鄧星星
達叔
林青霞
關之琳
5
import os
with open('./test.txt',mode='r',encoding='utf-8') as f1,open('test3.txt',mode='w',encoding='utf-8') as f2:
for line in f1:
s2 = line.replace('周','鄧')
f2.write(s2)
f1.close()
f2.close()
os.remove('./test.txt')
os.rename('./test3.txt','./test.txt')
文件修改前:
文件修改後: