python-文字操作和二進位制儲存
阿新 • • 發佈:2020-09-08
0x01 open方法
r read
w write
a append
b byte
test.txt內容為
yicunyiye
wutang
讀取test.txt
f = open('test.txt','r',encoding='utf-8')
text = f.read()
print(text)
讀取一行
f = open('test.txt','r',encoding='utf-8')
text = f.readline()
print(text)
全部
f = open('test.txt','r',encoding='utf-8') text = f.readlines() print(text)
輸出
['yicunyiye\n', 'wutang\n']
美化
f = open('test.txt','r',encoding='utf-8')
text = f.readlines()
for t in text:
print(t.strip().replace("\n",""))
輸出
yicunyiye
wutang
f = open('test.txt','r',encoding='utf-8') for i in range(3): text = f.readline() print(text.strip().replace("\n",""))
輸出同上
0x02 with open as
這種就不需要f.close()了
with open('test.txt','r',encoding='utf8') as f:
print(f.readlines())
寫入檔案
#w 不存在就建立 存在就覆蓋
with open('test_two.txt','w',encoding='utf8') as f:
f.write('yicunyiye')
追加檔案
#a 不存在就建立 存在就追加 with open('test_two.txt','a',encoding='utf8') as f: f.write('\nniubi')