【Head First Python】Python I/O

一、打开文件的两种方法

1,直接使用 open 方法

1 tasks = open('todos.txt')
2 for chore in tasks:
3     print(chore, end='')
4 task.close()

最后记得调用 close(),否则有可能出错.

2,使用 with 语句

1 with open('todos.txt') as task:
2     for chore in tasks:
3         print(chore, end='')

和第一种方法实现的是同一个功能,好处是不需要调用 close()。with 语句会自动调用。

二、read、readline、readlines 三种方法的区别

read() 读取全部文件内容,返回一个 str。

readline() 读取文件的一行,返回一个 str。

readlines() 读取全部文件内容,返回一个 list,list 中的每个元素就是文件的一行。

三、print 进阶

print 可以说是 Python 中最常用的函数了。这里介绍一些进阶功能。

print(*objects, sep=' ', end = '\n', file=sys.stdout)

*objects:允许传入多个参数。

sep:用来间隔多个对象,默认是空格。

end:用来设定以什么结尾,默认是'\n'。

file:用来设定写入的文件。

猜你喜欢

转载自www.cnblogs.com/bladeofstalin/p/11296809.html