python系列教程49

网友投稿 515 2022-10-20

python系列教程49

python系列教程49

在python中,要创建一个文件对象,需调用内置的open函数以字符串的形式传递给它一个文件名以及一个代表处理模式的字符串。例如,创建一个文本文件,可以传递其文件名以及’w’处理模式字符串来写数据

>>> f = open('data.txt','w') # Make a new file in output mode>>> f.write('Hello\n') # Write strings of bytes to it6>>> f.write('world\n') # Returns number of bytes written in Python 3.06>>> f.close() # Close to flush output buffers to disk

这样就在当前文件夹下创建了一个名为data.txt的文件,并向它写入文本。为了读出刚才所写的内容,重新以’r’处理模式打开文件,读取输入(如果在调用时忽略模式的话,将默认为r模式):

>>> f = open('data.txt') # 'r' is the default processing mode>>> text = f.read() # Read entire file into a string>>> text\n'Hello\nworld\n'>>> print(text) # print interprets control charactersHelloworld>>> text.split() # File content is always a string['Hello','world']

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Dilutions- 数据通信解耦框架
下一篇:前端项目框架和结构
相关文章

 发表评论

暂时没有评论,来抢沙发吧~