这篇是用来总结这段时间所学的所用的关于python3小tips,比较细微。主要是为了防止以后会遗忘掉这些而去重复搜索解决方法。
1.对于文件的处理
1.1打开文件
打开文件后,读写内容全都是字符串。
f=open(“filename”,”w”) 打开一个用于写入的文件,要写入内容时使用f.write(“内容”)
f=open(“filename”,”r”) 打开一个用于读的文件,读时使用f.read(),返回读取的到的字符串;
f=open(“filename”,”a”) 打开的文件既可用于读,也可用于写;
2.2文件对象的属性和方法
f.close() 关闭文件对象f,并将属性f.close设置为True;
f.close 文件已关闭,则返回True;
f.encoding byte与str之间进行转换时使用的编码;
f.fileno() 返回底层文件的文件描述符;
f.flush() 清空文件对象;
f.isatty() 如果文件对象与控制台关联,就返回True;
f.mode 文件对象打开时使用的模式;
f.name 文件对象f的文件名(如果有);
f.newlines 文本文件f中的换行字符串的类型;
f.__next__() 返回文件对象f的下一行;
f.peek(n) 返回n个字节,而不移动文件指针的位置;
f.readable() 如果f已经打开等待读取,则返回True;
f.read(count) 文件对象f中读取至多count个字节,如果没有指定count,就读取从当前文件指针直到最后的每个字节,以二进制模式时,返回bytes对象;以文件模式时,返回str对象;
f.readinto(ba) 将至多len(ba)个字节读入到bytearray ba中,并返回读入字节数,如果在文件结尾,就为0;
f.readline(count) 读取下一行,包括\n;
f.readlines(sizehint) 读入到文件结尾之前的所有行,并以列表形式返回;
f.seek(offset,whence) 如果没有给定whence,或其为os.SEEK_SET,就按给定的offset移动文件指针...
f.seekable() 如果f支持随机存取,就返回True;
f.tell() 返回当前指针位置;
f.truncate(size)截取文件到当前文件指针所在位置,如果给定size,就到size大小处;
f.writable() 如果f是为写操作而打开的,就返回True;
f.write(s) 将文本对象s写入到文件;
f.writelines(seq)将对象序列写入到文件;
2.引号内变量的使用
单个变量:
a = "helloworld"
print("a=%s" %a)
输出结果为a=helloworld
两个变量:
注:其中%s对应字符串,%d对应数值
a = "helloworld"
b = 123
print("the first demo is %s , take me %dhours" %(a,b))
输出结果为the first demo is helloworld , take me 123hours
多个变量:
a = "helloworld"
b = "123"
c = "enter"
print("first demo is %s, you should press %s to continue and the length is %s" %(a, c, b))
输出结果为first demo is helloworld, you should press enter to continue and the length is 123
3.对于字符串的分割
内置spilt函数即可分割字符串。
str = "this is string example....wow!!!"
print(str.split())
print(str.split('i', 1))
print(str.split('w'))
效果如下,返回数组:
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']