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",""))
输出同上
这种就不需要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')
手机扫一扫
移动阅读更方便
你可能感兴趣的文章