摸了一个星期鱼,博客也断更很久了 ,今天看了一点python文件读写,记录一下。
打开文件
使用open函数打开文件,函数的两个主要参数为文件名和打开模式,默认的打开模式为r(read读文件)
还有一种较为常用的打开模式为w(write写文件),注意使用w模式打开文件,如果文件不存在,会自动生成一个文件,如果已经存在,那么会删除文件中的所有内容,从头开始写入。还有很多打开模式,详见文字最底下的参考资料1。
file = open('test.txt', 'r') # 打开了同目录下的test.txt文件
file.close() # 关闭文件
使用完文件之后记得关闭文件,这是一个好习惯。
读文件
假设已经有文件D:\Python_workspace\test.txt且文件中已经有如下内容:
hello hesorchen !
hello python !
通过以下程序,可以读取文件中的所有内容,其中,read方法可以增加参数,表示读取的字符数/字节数(按照打开模式区分)
file = open('D:\\Python_workspace\\test.txt', 'r')
print(file.read()) # 读取所有的文件内容
file.close()
'''
Output:
hello hesorchen !
hello python !
'''
当然,我们还有其他的方式读取文件,例如readline()和readlines()。其中,readline()是读取一行,readlines()是读取整个文件,并且将文件内容一行一行的分开存储在list中。
file = open('D:\\Python_workspace\\test.txt', 'r')
print(file.readline()) # 读取一行
file.close()
'''
Output:
hello hesorchen !
'''
file = open('D:\\Python_workspace\\test.txt', 'r')
print(file.readlines()) # 读取全部
file.close()
'''
Output:
['hello hesorchen !\n', 'hello python !']
'''
另外,不得不提一个十分重要的seek()方法,他的作用是将文件指针移动到指定位置,该方法包含两个参数,第一个参数表示偏移量,第二个参数可以选择0/1/2,分别表示从文件头/当前位置/文件尾偏移
file = open('D:\\Python_workspace\\test.txt', 'rb')
file.seek(0, 0)
print(file.read(1))
file.seek(-1, 1)
print(file.read(1))
file.seek(-1, 2)
print(file.read(1))
file.close()
'''
Output:
b'h'
b'h'
b'!'
'''
写文件
写文件主要提两个方法:
write():向文件写入字符串
writellines():向文件写入字符串序列
另外注意w模式写文件会删除文件原有内容
file = open('D:\\Python_workspace\\test.txt', 'w')
str1 = 'qwq'
file.write(str1)
file.close()
file = open('D:\\Python_workspace\\test.txt', 'w')
str1 = ['abc\n','1234\n','cdef\n']
file.writelines(str1)
file.close()