文件是保存在磁盘上的,而我们对文件进行读写时又是通过系统来完成,只要是对文件进行操作都必须先打开文件。而每次打开文件后就会得到一个文件描述符,然后系统提供的接口就可以从这个文件对象中读取数据,或者写入数据。
使用Python经常会对文件读写操作,所以简单的文件操作是学习Python必会的技能。
能过Python内置的帮助查看命令的参数:
help(open)
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
1、写入文件
f = open('123.txt','w') #默认情况w写入文件,每次都会清空文件后再写入
for x in range(10):
f.write(str(x))
f.close() #打开文件记得关闭
如果文件’123.txt’不存在就会自动创建,保存路径,如果不加就保存在程序当前目录; w
只写,如果要一直追加就要使用参数a
,追加。
f = open('123.txt','a') #每执行一次都会执行追加内容到文件
for x in range(10):
f.write(str(x))
f.close()
上面写入文件是保存成一行的,如果我想把每个数字写入到文件时有间隔。”\n”换行,”\t”制表符
f = open('123.txt','w')
for x in range(10):
f.write(str(x) + '\n')
f.close()
这种方法直接open的话要记得关闭,所以更提倡使用with open
的方式,它会自动上下文切换,自动调用close()。
所以上面的写入文件可以修改成:
with open('123.txt','w') as f:
for x in range(10):
f.write(str(x))
f.close()
2、读写文件,把上面写入的文件内容读取出来;
f = open('123.txt','r')
for line in f:
print(line)
f.close()
但是直接读出上面的文件内容就会出现每行下都有一行空白行,因上面写入文件时后面加了’\n’换行。
f = open('123.txt','r')
for line in f:
print(line.strip()) #strip()可以去掉字符串后的的空白字符和换行符。
f.close()
使用with open
的方式也一样:
with open('123.txt','r') as f:
for line in f:
print(line.strip())
说明:
使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally
语句来确保最后能关闭文件。