python_读写文件
打开文件:
file_obj= open("file_name",modo)
modo:
r只读,w写 a 追加
file_obj = open("str.py",'r')
读文件
read 可以把整个文件当成一个str读入,read(字节数)可以读入多少个字节。
var = file_obj.read()
readline 把文件的一行当成一个str读入
var = file_obj.readline() readline( 读入的行数) 可以设定读入第几行。
readines 可以把整个文件的每一行当一个str读入到一个list中。
写入文件
file_obj= open('file_name',w)
file_obj.write(content_obj)
write 写入文件,write(str)
writelines 也是写入文件,不过他可以写入str list 元组。
file_obj = open('test.txt','w+')
str1 = 'nbm'
str2 = 'dffd'
file_obj.write(str1+'\n')
file_obj.write(str2+'\n')
file_obj.close()