python 读写文本数据

2022-05-18  本文已影响0人  孙广宁
5.1 可以使用open函数,配合rt参数
### 读取文件并加载成一行string
>>> with open('test.txt','rt') as f:
...     data = f.read()
...
>>>
>>> data
'111\n222\n333\n\n'
### 读取文件中的每一行
>>> with open('test.txt','rt') as f:
...     for line in f:
...         print(line)
...
111

222

333

>>> with open('test.txt','wt') as f:
...     f.write("ttt")
...     f.write("yyy")
>>> with open('test.txt','rt') as f:
...     f.read()
'tttyyy'
>>> with open('test.txt','wt') as f:
...     print('wt',file=f)
>>> with open('test.txt','rt') as f:
...     f.read()
'wt\n'
>>>
>>> with open('test.txt','rt',encoding='latin-1') as f:
...
>>> f = open('test.txt','rt')
>>> data=f.read()
>>> f.close()
>>> data
'wt\n'
>>>
上一篇下一篇

猜你喜欢

热点阅读