python系列教程49

154 阅读1分钟

朋友们,如需转载请标明出处:blog.csdn.net/jiangjunsho…

声明:在人工智能技术教学期间,不少学生向我提一些python相关的问题,所以为了让同学们掌握更多扩展知识更好的理解人工智能技术,我让助理负责分享这套python系列教程,希望能帮到大家!由于这套python教程不是由我所写,所以不如我的人工智能技术教学风趣幽默,学起来比较枯燥;但它的知识点还是讲到位的了,也值得阅读!

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

>>> f = open'data.txt','w'# Make a new file in output mode

>>> f.write('Hello\n'# Write strings of bytes to it

6

>>> f.write('world\n'# Returns number of bytes written in Python 3.0

6

>>> 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 characters

Hello

world



>>> text.split()                  # File content is always a string

['Hello','world']